Debian Codegraph @

src/Gui/PythonWrapper.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2021 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <limits>
25 #include <unordered_map>
26 #include <list>
27 #include <QAction>
28 #include <QApplication>
29 #include <QDir>
30 #include <QIcon>
31 #include <QPrinter>
32 #include <QWidget>
33
34
35 #include <QMetaType>
36
37 // Uncomment this block to remove PySide C++ support and switch to its Python interface
38 // #undef HAVE_SHIBOKEN2
39 // #undef HAVE_PYSIDE2
40 // #undef HAVE_SHIBOKEN6
41 // #undef HAVE_PYSIDE6
42
43 #include <FCConfig.h>
44
45 #ifdef FC_OS_WIN32
46 # undef max
47 # undef min
48 # ifdef _MSC_VER
49 # pragma warning(disable : 4099)
50 # pragma warning(disable : 4522)
51 # endif
52 #endif
53
54 #if defined(__clang__)
55 # pragma clang diagnostic push
56 # pragma clang diagnostic ignored "-Wmismatched-tags"
57 # pragma clang diagnostic ignored "-Wunused-parameter"
58 # if __clang_major__ > 3
59 # pragma clang diagnostic ignored "-Wkeyword-macro"
60 # endif
61 #elif defined(__GNUC__)
62 # pragma GCC diagnostic push
63 # pragma GCC diagnostic ignored "-Wunused-parameter"
64 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
65 #endif
66
67 //-----------------------------------------------------------------------------
68 //
69 // shiboken2 and PySide2 specific defines and includes
70 //
71
72 // class and struct used for SbkObject
73 //
74 #ifdef HAVE_SHIBOKEN2
75 # define HAVE_SHIBOKEN
76 # ifdef HAVE_PYSIDE2
77 # define HAVE_PYSIDE
78
79 // Include shiboken first to get the version
80 # include <shiboken.h>
81
82 // Do not use SHIBOKEN_MICRO_VERSION; it might contain a dot
83 # define SHIBOKEN_FULL_VERSION QT_VERSION_CHECK(SHIBOKEN_MAJOR_VERSION, SHIBOKEN_MINOR_VERSION, 0)
84
85 # include <pyside2_qtcore_python.h>
86 # include <pyside2_qtgui_python.h>
87 # include <pyside2_qtwidgets_python.h>
88 # endif // HAVE_PYSIDE2
89 #endif // HAVE_SHIBOKEN2
90
91 //-----------------------------------------------------------------------------
92 //
93 // shiboken6 and PySide6 specific defines and includes
94 //
95
96 // class and struct used for SbkObject
97 //
98 #ifdef HAVE_SHIBOKEN6
99 # define HAVE_SHIBOKEN
100 # ifdef HAVE_PYSIDE6
101 # define HAVE_PYSIDE
102 # define HAVE_SHIBOKEN_TYPE_FOR_TYPENAME
103 # endif // HAVE_PYSIDE6
104 # include <sbkversion.h>
105 # define SHIBOKEN_FULL_VERSION QT_VERSION_CHECK(SHIBOKEN_MAJOR_VERSION, SHIBOKEN_MINOR_VERSION, 0)
106 # if (SHIBOKEN_FULL_VERSION >= QT_VERSION_CHECK(6, 7, 0))
107 # define HAVE_SHIBOKEN_TYPEINITSTRUCT
108 # endif
109 #endif // HAVE_SHIBOKEN6
110
111 //-----------------------------------------------------------------------------
112
113 #ifdef HAVE_SHIBOKEN
114 # undef _POSIX_C_SOURCE
115 # undef _XOPEN_SOURCE
116 # include <basewrapper.h>
117 # include <sbkconverter.h>
118 # include <sbkmodule.h>
119 # include <shiboken.h>
120 #endif // HAVE_SHIBOKEN
121
122 #ifdef HAVE_PYSIDE
123 # include <signalmanager.h>
124 #endif // HAVE_PYSIDE
125
126 //-----------------------------------------------------------------------------
127
128 #if defined(__clang__)
129 # pragma clang diagnostic pop
130 #elif defined(__GNUC__)
131 # pragma GCC diagnostic pop
132 #endif
133
134 // Must be imported after PySide headers
135 #include <QGraphicsItem>
136 #include <QGraphicsObject>
137
138
139 #include <App/Application.h>
140 #include <Base/Interpreter.h>
141 #include <Base/Quantity.h>
142 #include <Base/QuantityPy.h>
143
144 #include "PythonWrapper.h"
145 #include "UiLoader.h"
146 #include "MetaTypes.h"
147
148 // NOLINTBEGIN
149 #if defined(HAVE_SHIBOKEN2)
150 PyTypeObject** SbkPySide2_QtCoreTypes = nullptr;
151 PyTypeObject** SbkPySide2_QtGuiTypes = nullptr;
152 PyTypeObject** SbkPySide2_QtWidgetsTypes = nullptr;
153 PyTypeObject** SbkPySide2_QtPrintSupportTypes = nullptr;
154 PyTypeObject** SbkPySide2_QtUiToolsTypes = nullptr;
155 constexpr auto& SbkPySide_QtCoreTypes = SbkPySide2_QtCoreTypes;
156 constexpr auto& SbkPySide_QtGuiTypes = SbkPySide2_QtGuiTypes;
157 constexpr auto& SbkPySide_QtWidgetsTypes = SbkPySide2_QtWidgetsTypes;
158 constexpr auto& SbkPySide_QtPrintSupportTypes = SbkPySide2_QtPrintSupportTypes;
159 constexpr auto& SbkPySide_QtUiToolsTypes = SbkPySide2_QtUiToolsTypes;
160 # if !defined(HAVE_PYSIDE2)
161 constexpr const char* ModuleShiboken = "shiboken2";
162 # endif
163 constexpr const char* ModulePySide = "PySide2";
164 #elif defined(HAVE_SHIBOKEN6)
165 # ifdef HAVE_SHIBOKEN_TYPEINITSTRUCT
166 Shiboken::Module::TypeInitStruct* SbkPySide6_QtCoreTypes = nullptr;
167 Shiboken::Module::TypeInitStruct* SbkPySide6_QtGuiTypes = nullptr;
168 Shiboken::Module::TypeInitStruct* SbkPySide6_QtWidgetsTypes = nullptr;
169 Shiboken::Module::TypeInitStruct* SbkPySide6_QtPrintSupportTypes = nullptr;
170 Shiboken::Module::TypeInitStruct* SbkPySide6_QtUiToolsTypes = nullptr;
171 # else
172 PyTypeObject** SbkPySide6_QtCoreTypes = nullptr;
173 PyTypeObject** SbkPySide6_QtGuiTypes = nullptr;
174 PyTypeObject** SbkPySide6_QtWidgetsTypes = nullptr;
175 PyTypeObject** SbkPySide6_QtPrintSupportTypes = nullptr;
176 PyTypeObject** SbkPySide6_QtUiToolsTypes = nullptr;
177 # endif
178 constexpr auto& SbkPySide_QtCoreTypes = SbkPySide6_QtCoreTypes;
179 constexpr auto& SbkPySide_QtGuiTypes = SbkPySide6_QtGuiTypes;
180 constexpr auto& SbkPySide_QtWidgetsTypes = SbkPySide6_QtWidgetsTypes;
181 constexpr auto& SbkPySide_QtPrintSupportTypes = SbkPySide6_QtPrintSupportTypes;
182 constexpr auto& SbkPySide_QtUiToolsTypes = SbkPySide6_QtUiToolsTypes;
183 # if !defined(HAVE_PYSIDE6)
184 constexpr const char* ModuleShiboken = "shiboken6";
185 # endif
186 constexpr const char* ModulePySide = "PySide6";
187 #else
188 static PyTypeObject** SbkPySide_DummyTypes;
189 constexpr auto& SbkPySide_QtCoreTypes = SbkPySide_DummyTypes;
190 constexpr auto& SbkPySide_QtGuiTypes = SbkPySide_DummyTypes;
191 constexpr auto& SbkPySide_QtWidgetsTypes = SbkPySide_DummyTypes;
192 constexpr auto& SbkPySide_QtPrintSupportTypes = SbkPySide_DummyTypes;
193 constexpr auto& SbkPySide_QtUiToolsTypes = SbkPySide_DummyTypes;
194 # if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
195 constexpr const char* ModuleShiboken = "shiboken2";
196 constexpr const char* ModulePySide = "PySide2";
197 # else
198 constexpr const char* ModuleShiboken = "shiboken6";
199 constexpr const char* ModulePySide = "PySide6";
200 # endif
201 #endif
202 // NOLINTEND
203
204 using namespace Gui;
205
206 #if defined(HAVE_SHIBOKEN)
207
208 /**
209 Example:
210 \code
211 ui = FreeCADGui.UiLoader()
212 w = ui.createWidget("Gui::InputField")
213 w.show()
214 w.property("quantity")
215 \endcode
216 */
217
218 PyObject* toPythonFuncQuantityTyped(Base::Quantity cpx)
219 {
220 return new Base::QuantityPy(new Base::Quantity(cpx));
221 }
222
223 PyObject* toPythonFuncQuantity(const void* cpp)
224 {
225 return toPythonFuncQuantityTyped(*static_cast<const Base::Quantity*>(cpp));
226 }
227
228 void toCppPointerConvFuncQuantity(PyObject* pyobj, void* cpp)
229 {
230 *static_cast<Base::Quantity*>(cpp) = *static_cast<Base::QuantityPy*>(pyobj)->getQuantityPtr();
231 }
232
233 PythonToCppFunc toCppPointerCheckFuncQuantity(PyObject* obj)
234 {
235 if (PyObject_TypeCheck(obj, &(Base::QuantityPy::Type))) {
236 return toCppPointerConvFuncQuantity;
237 }
238 return nullptr;
239 }
240
241 void BaseQuantity_PythonToCpp_QVariant(PyObject* pyIn, void* cppOut)
242 {
243 Base::Quantity* q = static_cast<Base::QuantityPy*>(pyIn)->getQuantityPtr();
244 *((QVariant*)cppOut) = QVariant::fromValue<Base::Quantity>(*q);
245 }
246
247 PythonToCppFunc isBaseQuantity_PythonToCpp_QVariantConvertible(PyObject* obj)
248 {
249 if (PyObject_TypeCheck(obj, &(Base::QuantityPy::Type))) {
250 return BaseQuantity_PythonToCpp_QVariant;
251 }
252 return nullptr;
253 }
254
255 # if defined(HAVE_PYSIDE)
256 Base::Quantity convertWrapperToQuantity(const PySide::PyObjectWrapper& w)
257 {
258 auto pyIn = static_cast<PyObject*>(w);
259 if (PyObject_TypeCheck(pyIn, &(Base::QuantityPy::Type))) {
260 return *static_cast<Base::QuantityPy*>(pyIn)->getQuantityPtr();
261 }
262
263 return Base::Quantity(std::numeric_limits<double>::quiet_NaN());
264 }
265 # endif
266
267 void registerTypes()
268 {
269 SbkConverter* convert
270 = Shiboken::Conversions::createConverter(&Base::QuantityPy::Type, toPythonFuncQuantity);
271 Shiboken::Conversions::setPythonToCppPointerFunctions(
272 convert,
273 toCppPointerConvFuncQuantity,
274 toCppPointerCheckFuncQuantity
275 );
276 Shiboken::Conversions::registerConverterName(convert, "Base::Quantity");
277
278 SbkConverter* qvariant_conv = Shiboken::Conversions::getConverter("QVariant");
279 if (qvariant_conv) {
280 // The type QVariant already has a converter from PyBaseObject_Type which will
281 // come before our own converter.
282 Shiboken::Conversions::addPythonToCppValueConversion(
283 qvariant_conv,
284 BaseQuantity_PythonToCpp_QVariant,
285 isBaseQuantity_PythonToCpp_QVariantConvertible
286 );
287 }
288
289 # if defined(HAVE_PYSIDE)
290 QMetaType::registerConverter<PySide::PyObjectWrapper, Base::Quantity>(&convertWrapperToQuantity);
291 # endif
292 }
293 #endif
294
295 // --------------------------------------------------------
296
297 namespace Gui
298 {
299
300 static std::string getPySideModuleName(const std::string& moduleName)
301 {
302 std::string name(ModulePySide);
303 name += '.';
304 name += moduleName;
305
306 return name;
307 }
308
309 #ifdef HAVE_SHIBOKEN_TYPEINITSTRUCT
310 static bool loadPySideModule(const std::string& moduleName, Shiboken::Module::TypeInitStruct*& types)
311 #else
312 static bool loadPySideModule(const std::string& moduleName, PyTypeObject**& types)
313 #endif
314 {
315 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
316 if (!types) {
317 Shiboken::AutoDecRef requiredModule(
318 Shiboken::Module::import(getPySideModuleName(moduleName).c_str())
319 );
320 if (requiredModule.isNull()) {
321 return false;
322 }
323 types = Shiboken::Module::getTypes(requiredModule);
324 }
325 #else
326 Q_UNUSED(moduleName)
327 Q_UNUSED(types)
328 #endif
329 return true;
330 }
331
332 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
333 template<typename qttype>
334 # if defined(HAVE_SHIBOKEN2)
335 SbkObjectType*
336 # else
337 PyTypeObject*
338 # endif
339 getPyTypeObjectForTypeName()
340 {
341 # if defined(HAVE_SHIBOKEN_TYPE_FOR_TYPENAME)
342 # if defined(HAVE_SHIBOKEN2)
343 auto sbkType = Shiboken::ObjectType::typeForTypeName(typeid(qttype).name());
344 return reinterpret_cast<SbkObjectType*>(&sbkType->type);
345 # else
346 return Shiboken::ObjectType::typeForTypeName(typeid(qttype).name());
347 # endif
348 # else
349 # if defined(HAVE_SHIBOKEN2)
350 return reinterpret_cast<SbkObjectType*>(Shiboken::SbkType<qttype>());
351 # else
352 return Shiboken::SbkType<qttype>();
353 # endif
354 # endif
355 }
356
357 template<typename qttype>
358 qttype* qt_getCppType(PyObject* pyobj)
359 {
360 auto type = getPyTypeObjectForTypeName<qttype>();
361 if (type) {
362 if (Shiboken::Object::checkType(pyobj)) {
363 auto skbobj = reinterpret_cast<SbkObject*>(pyobj);
364 auto pytypeobj = reinterpret_cast<PyTypeObject*>(type);
365 return static_cast<qttype*>(Shiboken::Object::cppPointer(skbobj, pytypeobj));
366 }
367 }
368 return nullptr;
369 }
370
371 /*!
372 * \brief The WrapperManager class
373 * This is a helper class that records the Python wrappers of a QObject and invalidates
374 * them when the QObject is about to be destroyed.
375 * This is to make sure that if the Python wrapper doesn't own the QObject it won't be notified
376 * if the QObject is destroyed.
377 * \code
378 * ui = Gui.UiLoader()
379 * lineedit = ui.createWidget("QLineEdit")
380 * lineedit.deleteLater()
381 * # Make sure this won't crash
382 * lineedit.show()
383 * \endcode
384 */
385 class WrapperManager: public QObject
386 {
387
388 public:
389 static WrapperManager& instance()
390 {
391 static WrapperManager singleton;
392 return singleton;
393 }
394 /*!
395 * \brief addQObject
396 * \param obj
397 * \param pyobj
398 * Connects destruction event of a QObject with invalidation of its PythonWrapper via a helper
399 * QObject.
400 */
401 void addQObject(QObject* obj, PyObject* pyobj)
402 {
403 // static array to contain created connections so they can be safely disconnected later
404 static std::map<QObject*, QMetaObject::Connection> connections = {};
405
406 const auto PyW_uniqueName = QString::number(reinterpret_cast<quintptr>(pyobj));
407 auto PyW_invalidator = findChild<QObject*>(PyW_uniqueName, Qt::FindDirectChildrenOnly);
408
409 if (PyW_invalidator == nullptr) {
410 PyW_invalidator = new QObject(this);
411 PyW_invalidator->setObjectName(PyW_uniqueName);
412
413 Py_INCREF(pyobj);
414 }
415 else if (connections.contains(PyW_invalidator)) {
416 disconnect(connections[PyW_invalidator]);
417 connections.erase(PyW_invalidator);
418 }
419
420 auto destroyedFun = [pyobj]() {
421 Base::PyGILStateLocker lock;
422
423 if (auto sbkPtr = reinterpret_cast<SbkObject*>(pyobj); sbkPtr != nullptr) {
424 Shiboken::Object::setValidCpp(sbkPtr, false);
425 }
426 else {
427 Base::Console().developerError(
428 "WrapperManager",
429 "A QObject has just been destroyed after its Pythonic wrapper.\n"
430 );
431 }
432
433 Py_DECREF(pyobj);
434 };
435
436 connections[PyW_invalidator]
437 = connect(PyW_invalidator, &QObject::destroyed, this, destroyedFun);
438 connect(obj, &QObject::destroyed, PyW_invalidator, &QObject::deleteLater);
439 }
440
441 private:
442 void wrapQApplication()
443 {
444 // We have to explicitly hold a reference to the wrapper of the QApplication
445 // as otherwise it can happen that when running the gc the program crashes
446 // The code snippet below caused a crash on older versions:
447 // mw = Gui.getMainWindow()
448 // mw.style()
449 // import gc
450 // gc.collect()
451 auto type = getPyTypeObjectForTypeName<QApplication>();
452 if (type) {
453 PyObject* pyobj = Shiboken::Object::newObject(type, qApp, false, false, "QApplication");
454 addQObject(qApp, pyobj);
455 }
456 }
457
458 WrapperManager()
459 {
460 wrapQApplication();
461 }
462 ~WrapperManager() override = default;
463 };
464
465 #else
466
467 static std::string formatModuleError(const std::string& name)
468 {
469 std::string error = "Cannot load " + name + " module";
470 return error;
471 }
472
473 static PyObject* importShiboken()
474 {
475 PyObject* obj = PyImport_ImportModule(ModuleShiboken);
476 if (obj) {
477 return obj;
478 }
479
480 throw Py::Exception(PyExc_ImportError, formatModuleError(ModuleShiboken));
481 }
482
483 static PyObject* importPySide(const std::string& moduleName)
484 {
485 std::string name = getPySideModuleName(moduleName);
486 PyObject* obj = PyImport_ImportModule(name.c_str());
487 if (obj) {
488 return obj;
489 }
490
491 throw Py::Exception(PyExc_ImportError, formatModuleError(name));
492 }
493
494 template<typename qttype>
495 qttype* qt_getCppType(PyObject* pyobj)
496 {
497 // https://github.com/PySide/Shiboken/blob/master/shibokenmodule/typesystem_shiboken.xml
498 Py::Module mainmod(importShiboken(), true);
499 Py::Callable func = mainmod.getDict().getItem("getCppPointer");
500 if (func.isNull()) {
501 throw Py::RuntimeError("Failed to get C++ pointer");
502 }
503
504 Py::Tuple arguments(1);
505 arguments[0] = Py::Object(pyobj); // PySide pointer
506 Py::Tuple result(func.apply(arguments));
507 return reinterpret_cast<qttype*>(PyLong_AsVoidPtr(result[0].ptr()));
508 }
509
510 template<typename qttype>
511 Py::Object qt_wrapInstance(qttype object, const std::string& className, const std::string& moduleName)
512 {
513 Py::Module mainmod(importShiboken(), true);
514 Py::Callable func = mainmod.getDict().getItem("wrapInstance");
515 if (func.isNull()) {
516 // Failure will be handled in the calling instance
517 return func;
518 }
519
520 Py::Module qtmod(importPySide(moduleName));
521 Py::Object item = qtmod.getDict().getItem(className);
522 if (item.isNull()) {
523 // Failure will be handled in the calling instance
524 return item;
525 }
526
527 Py::Tuple arguments(2);
528 arguments[0] = Py::asObject(PyLong_FromVoidPtr((void*)object));
529 arguments[1] = item;
530
531 return func.apply(arguments);
532 }
533
534 const char* qt_identifyType(QObject* ptr, const std::string& moduleName)
535 {
536 Py::Module qtmod(importPySide(moduleName));
537 const QMetaObject* metaObject = ptr->metaObject();
538 while (metaObject) {
539 const char* className = metaObject->className();
540 if (qtmod.getDict().hasKey(className)) {
541 return className;
542 }
543 metaObject = metaObject->superClass();
544 }
545
546 return nullptr;
547 }
548
549 #endif
550
551 } // namespace Gui
552
553 // --------------------------------------------------------
554
555 PythonWrapper::PythonWrapper()
556 {
557 #if defined(HAVE_SHIBOKEN)
558 static bool init;
559 if (!init) {
560 init = true;
561 registerTypes();
562 }
563 #endif
564 }
565
566 bool PythonWrapper::toCString(const Py::Object& pyobject, std::string& str)
567 {
568 if (PyUnicode_Check(pyobject.ptr())) {
569 PyObject* unicode = PyUnicode_AsUTF8String(pyobject.ptr());
570 str = PyBytes_AsString(unicode);
571 Py_DECREF(unicode);
572 return true;
573 }
574 else if (PyBytes_Check(pyobject.ptr())) {
575 str = PyBytes_AsString(pyobject.ptr());
576 return true;
577 }
578 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
579 if (Shiboken::String::check(pyobject.ptr())) {
580 const char* s = Shiboken::String::toCString(pyobject.ptr());
581 if (s) {
582 str = s;
583 }
584 return true;
585 }
586 #endif
587 return false;
588 }
589
590 QObject* PythonWrapper::toQObject(const Py::Object& pyobject)
591 {
592 return qt_getCppType<QObject>(pyobject.ptr());
593 }
594
595 qsizetype PythonWrapper::tryEnum(PyObject* pyPtr)
596 {
597 if (PyObject* number = PyNumber_Long(pyPtr)) {
598 Py::Long longObj(number, true);
599 return longObj.as_long();
600 }
601
602 // if PyNumber_Long failed then an exception is set
603 PyErr_Clear();
604
605 Py::Object object(pyPtr);
606 if (object.hasAttr(std::string("value"))) {
607 Py::Long longObj(object.getAttr(std::string("value")));
608 return longObj.as_long();
609 }
610
611 return 0;
612 }
613
614 qsizetype PythonWrapper::toEnum(PyObject* pyPtr)
615 {
616 try {
617 return tryEnum(pyPtr);
618 }
619 catch (Py::Exception&) {
620 Base::PyException e;
621 e.reportException();
622 return 0;
623 }
624 }
625
626 qsizetype PythonWrapper::toEnum(const Py::Object& pyobject)
627 {
628 return toEnum(pyobject.ptr());
629 }
630
631 Py::Object PythonWrapper::tryToStandardButton(qsizetype value)
632 {
633 std::stringstream cmd;
634 cmd << "from PySide import QtWidgets\n";
635 cmd << "btn = QtWidgets.QDialogButtonBox.StandardButton(" << value << ")";
636 return Py::asObject(Base::Interpreter().getValue(cmd.str().c_str(), "btn"));
637 }
638
639 Py::Object PythonWrapper::toStandardButton(qsizetype value)
640 {
641 try {
642 return tryToStandardButton(value);
643 }
644 catch (Py::Exception& e) {
645 e.clear();
646 return Py::Long(value);
647 }
648 }
649
650 QGraphicsItem* PythonWrapper::toQGraphicsItem(PyObject* pyPtr)
651 {
652 return qt_getCppType<QGraphicsItem>(pyPtr);
653 }
654
655 QGraphicsItem* PythonWrapper::toQGraphicsItem(const Py::Object& pyobject)
656 {
657 return toQGraphicsItem(pyobject.ptr());
658 }
659
660 QGraphicsObject* PythonWrapper::toQGraphicsObject(PyObject* pyPtr)
661 {
662 return qt_getCppType<QGraphicsObject>(pyPtr);
663 }
664
665 QGraphicsObject* PythonWrapper::toQGraphicsObject(const Py::Object& pyobject)
666 {
667 return toQGraphicsObject(pyobject.ptr());
668 }
669
670 Py::Object PythonWrapper::fromQImage(const QImage& img)
671 {
672 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
673 auto type = getPyTypeObjectForTypeName<QImage>();
674 if (type) {
675 PyObject* pyobj = Shiboken::Conversions::copyToPython(type, const_cast<QImage*>(&img));
676 return Py::asObject(pyobj);
677 }
678 #else
679 // Access shiboken/PySide via Python
680 Py::Object obj = qt_wrapInstance<const QImage*>(&img, "QImage", "QtGui");
681 if (!obj.isNull()) {
682 return obj;
683 }
684 #endif
685 throw Py::RuntimeError("Failed to wrap image");
686 }
687
688 QImage* PythonWrapper::toQImage(PyObject* pyobj)
689 {
690 return qt_getCppType<QImage>(pyobj);
691 }
692
693 Py::Object PythonWrapper::fromQIcon(const QIcon* icon)
694 {
695 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
696 auto type = getPyTypeObjectForTypeName<QIcon>();
697 if (type) {
698 const char* typeName = typeid(*const_cast<QIcon*>(icon)).name();
699 PyObject* pyobj
700 = Shiboken::Object::newObject(type, const_cast<QIcon*>(icon), true, false, typeName);
701 return Py::asObject(pyobj);
702 }
703 #else
704 // Access shiboken/PySide via Python
705 Py::Object obj = qt_wrapInstance<const QIcon*>(icon, "QIcon", "QtGui");
706 if (!obj.isNull()) {
707 return obj;
708 }
709 #endif
710 throw Py::RuntimeError("Failed to wrap icon");
711 }
712
713 QIcon* PythonWrapper::toQIcon(PyObject* pyobj)
714 {
715 return qt_getCppType<QIcon>(pyobj);
716 }
717
718 Py::Object PythonWrapper::fromQDir(const QDir& dir)
719 {
720 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
721 auto type = getPyTypeObjectForTypeName<QDir>();
722 if (type) {
723 const char* typeName = typeid(dir).name();
724 PyObject* pyobj
725 = Shiboken::Object::newObject(type, const_cast<QDir*>(&dir), false, false, typeName);
726 return Py::asObject(pyobj);
727 }
728 #else
729 // Access shiboken/PySide via Python
730 Py::Object obj = qt_wrapInstance<const QDir*>(&dir, "QDir", "QtGui");
731 if (!obj.isNull()) {
732 return obj;
733 }
734 #endif
735 throw Py::RuntimeError("Failed to wrap directory");
736 }
737
738 QDir* PythonWrapper::toQDir(PyObject* pyobj)
739 {
740 return qt_getCppType<QDir>(pyobj);
741 }
742
743 Py::Object PythonWrapper::fromQAction(QAction* action)
744 {
745 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
746 // Access shiboken/PySide via C++
747 auto type = getPyTypeObjectForTypeName<QAction>();
748 if (type) {
749 PyObject* pyobj = Shiboken::Object::newObject(type, action, false, false, "QAction");
750 WrapperManager::instance().addQObject(action, pyobj);
751 return Py::asObject(pyobj);
752 }
753 #else
754 // Access shiboken/PySide via Python
755 # if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
756 constexpr const char* qtModWithQAction = "QtWidgets";
757 # else
758 constexpr const char* qtModWithQAction = "QtGui";
759 # endif
760 Py::Object obj = qt_wrapInstance<QAction*>(action, "QAction", qtModWithQAction);
761 if (!obj.isNull()) {
762 return obj;
763 }
764 #endif
765 throw Py::RuntimeError("Failed to wrap action");
766 }
767
768 Py::Object PythonWrapper::fromQPrinter(QPrinter* printer)
769 {
770 if (!printer) {
771 return Py::None();
772 }
773 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
774 // Access shiboken/PySide via C++
775 auto type = getPyTypeObjectForTypeName<QPrinter>();
776 if (!type) {
777 // XXX: Why is QPrinter special?
778 # if defined(HAVE_SHIBOKEN2)
779 type = reinterpret_cast<SbkObjectType*>(Shiboken::Conversions::getPythonTypeObject("QPrinter"));
780 # else
781 type = Shiboken::Conversions::getPythonTypeObject("QPrinter");
782 # endif
783 }
784 if (type) {
785 PyObject* pyobj = Shiboken::Object::newObject(type, printer, false, false, "QPrinter");
786 return Py::asObject(pyobj);
787 }
788 #else
789 // Access shiboken/PySide via Python
790 Py::Object obj = qt_wrapInstance<QPrinter*>(printer, "QPrinter", "QtCore");
791 if (!obj.isNull()) {
792 return obj;
793 }
794 #endif
795 throw Py::RuntimeError("Failed to wrap printer");
796 }
797
798 Py::Object PythonWrapper::fromQObject(QObject* object, const char* className)
799 {
800 if (!object) {
801 return Py::None();
802 }
803 const char* typeName;
804 if (className) {
805 typeName = className;
806 }
807 else {
808 typeName = object->metaObject()->className();
809 }
810 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
811 // Access shiboken/PySide via C++
812 auto type = getPyTypeObjectForTypeName<QObject>();
813 if (type) {
814 PyObject* pyobj = Shiboken::Object::newObject(type, object, false, false, typeName);
815 WrapperManager::instance().addQObject(object, pyobj);
816 return Py::asObject(pyobj);
817 }
818 #else
819 // Access shiboken/PySide via Python
820 Py::Object obj = qt_wrapInstance<QObject*>(object, typeName, "QtCore");
821 if (!obj.isNull()) {
822 return obj;
823 }
824 #endif
825 throw Py::RuntimeError("Failed to wrap object");
826 }
827
828 Py::Object PythonWrapper::fromQWidget(QWidget* widget, const char* className)
829 {
830 const char* typeName;
831 if (className) {
832 typeName = className;
833 }
834 else {
835 typeName = widget->metaObject()->className();
836 }
837 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
838 // Access shiboken/PySide via C++
839 auto type = getPyTypeObjectForTypeName<QWidget>();
840 if (type) {
841 PyObject* pyobj = Shiboken::Object::newObject(type, widget, false, false, typeName);
842 WrapperManager::instance().addQObject(widget, pyobj);
843 return Py::asObject(pyobj);
844 }
845 #else
846 // Access shiboken/PySide via Python
847 Py::Object obj = qt_wrapInstance<QWidget*>(widget, typeName, "QtWidgets");
848 if (!obj.isNull()) {
849 return obj;
850 }
851 #endif
852 throw Py::RuntimeError("Failed to wrap widget");
853 }
854
855 const char* PythonWrapper::getWrapperName(QObject* obj) const
856 {
857 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
858 const QMetaObject* meta = obj->metaObject();
859 while (meta) {
860 const char* typeName = meta->className();
861 PyTypeObject* exactType = Shiboken::Conversions::getPythonTypeObject(typeName);
862 if (exactType) {
863 return typeName;
864 }
865 meta = meta->superClass();
866 }
867 #else
868 QUiLoader ui;
869 QStringList names = ui.availableWidgets();
870 const QMetaObject* meta = obj->metaObject();
871 while (meta) {
872 const char* typeName = meta->className();
873 if (names.indexOf(QLatin1String(typeName)) >= 0) {
874 return typeName;
875 }
876 meta = meta->superClass();
877 }
878 #endif
879 return "QObject";
880 }
881
882 bool PythonWrapper::loadCoreModule()
883 {
884 return loadPySideModule("QtCore", SbkPySide_QtCoreTypes);
885 }
886
887 bool PythonWrapper::loadGuiModule()
888 {
889 return loadPySideModule("QtGui", SbkPySide_QtGuiTypes);
890 }
891
892 bool PythonWrapper::loadWidgetsModule()
893 {
894 return loadPySideModule("QtWidgets", SbkPySide_QtWidgetsTypes);
895 }
896
897 bool PythonWrapper::loadPrintSupportModule()
898 {
899 return loadPySideModule("QtPrintSupport", SbkPySide_QtPrintSupportTypes);
900 }
901
902 bool PythonWrapper::loadUiToolsModule()
903 {
904 return loadPySideModule("QtUiTools", SbkPySide_QtUiToolsTypes);
905 }
906
907 void PythonWrapper::createChildrenNameAttributes(PyObject* root, QObject* object)
908 {
909 Q_FOREACH (QObject* child, object->children()) {
910 const QByteArray name = child->objectName().toLocal8Bit();
911
912 if (!name.isEmpty() && !name.startsWith("_") && !name.startsWith("qt_")) {
913 bool hasAttr = PyObject_HasAttrString(root, name.constData());
914 if (!hasAttr) {
915 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
916 Shiboken::AutoDecRef pyChild(
917 Shiboken::Conversions::pointerToPython(getPyTypeObjectForTypeName<QObject>(), child)
918 );
919 PyObject_SetAttrString(root, name.constData(), pyChild);
920 #else
921 const char* className = qt_identifyType(child, "QtWidgets");
922 if (!className) {
923 if (qobject_cast<QWidget*>(child)) {
924 className = "QWidget";
925 }
926 else {
927 className = "QObject";
928 }
929 }
930
931 Py::Object pyChild(qt_wrapInstance<QObject*>(child, className, "QtWidgets"));
932 if (!pyChild.isNull()) {
933 PyObject_SetAttrString(root, name.constData(), pyChild.ptr());
934 }
935 #endif
936 }
937 createChildrenNameAttributes(root, child);
938 }
939 createChildrenNameAttributes(root, child);
940 }
941 }
942
943 void PythonWrapper::setParent(PyObject* pyWdg, QObject* parent)
944 {
945 #if defined(HAVE_SHIBOKEN) && defined(HAVE_PYSIDE)
946 if (parent) {
947 Shiboken::AutoDecRef pyParent(
948 Shiboken::Conversions::pointerToPython(getPyTypeObjectForTypeName<QWidget>(), parent)
949 );
950 Shiboken::Object::setParent(pyParent, pyWdg);
951 }
952 #else
953 Q_UNUSED(pyWdg);
954 Q_UNUSED(parent);
955 #endif
956 }