Debian Codegraph @

src/Base/PyObjectBase.h

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /***************************************************************************
4 * Copyright (c) 2002 Jürgen Riegel <[email protected]> *
5 * *
6 * This file is part of the FreeCAD CAx development system. *
7 * *
8 * This library is free software; you can redistribute it and/or *
9 * modify it under the terms of the GNU Library General Public *
10 * License as published by the Free Software Foundation; either *
11 * version 2 of the License, or (at your option) any later version. *
12 * *
13 * This library is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU Library General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Library General Public *
19 * License along with this library; see the file COPYING.LIB. If not, *
20 * write to the Free Software Foundation, Inc., 59 Temple Place, *
21 * Suite 330, Boston, MA 02111-1307, USA *
22 * *
23 ***************************************************************************/
24
25 #ifndef BASE_PYOBJECTBASE_H
26 #define BASE_PYOBJECTBASE_H
27
28 // clang-format off
29 // NOLINTBEGIN(cppcoreguidelines-macro-usage)
30 #include <bitset>
31 #include <cstring>
32 #include <CXX/Objects.hxx>
33
34 #include "Exception.h"
35
36 /** Python static class macro for definition
37 * sets up a static function entry in a class inheriting
38 * from PyObjectBase. It's a pure convenience macro. You can also do
39 * it by hand if you want. It looks like that:
40 * \code
41 * static PyObject* X (PyObject *self,PyObject *args,PyObject *kwd);
42 * \endcode
43 * @param SFUNC is the static method name (use what you want)
44 * @see PYFUNCIMP_S
45 * @see FCPythonExport
46 */
47 #define PYFUNCDEF_S(SFUNC) static PyObject* SFUNC (PyObject *self,PyObject *args,PyObject *kwd)
48
49
50 /** Python static class macro for implementation
51 * used to set up a implementation for PYFUNCDEF_S definition.
52 * Its a pure convenience macro. You can also do
53 * it by hand if you want. It looks like that:
54 * \code
55 * PyObject* CLASS::SFUNC (PyObject *self,PyObject *args,PyObject *kwd)
56 * \endcode
57 * see PYFUNCDEF_S for details
58 * @param CLASS is the class in which the macro take place.
59 * @param SFUNC is the object method get implemented
60 * @see PYFUNCDEF_S
61 * @see FCPythonExport
62 */
63 #define PYFUNCIMP_S(CLASS,SFUNC) PyObject* CLASS::SFUNC (PyObject *self,PyObject *args,PyObject *kwd)
64
65
66 /** Macro for initialization function of Python modules.
67 */
68 #define PyMOD_INIT_FUNC(name) PyMODINIT_FUNC PyInit_##name(void)
69 #define PyMOD_Return(name) return name
70
71
72 /*------------------------------
73 * Basic defines
74 ------------------------------*/
75 //typedef const char * version; // define "version"
76
77
78 namespace Base
79 {
80
81 inline int streq(const char *A, const char *B) // define "streq"
82 { return strcmp(A,B) == 0;}
83
84
85 inline void Assert(int expr, char *msg) // C++ assert
86 {
87 if (!expr)
88 {
89 fprintf(stderr, "%s\n", msg);
90 exit(-1);
91 };
92 }
93
94 inline PyObject* getTypeAsObject(PyTypeObject* type) {
95 // See https://en.cppreference.com/w/cpp/string/byte/memcpy
96 // and https://en.cppreference.com/w/cpp/language/reinterpret_cast
97 PyObject* obj{};
98 std::memcpy(&obj, &type, sizeof type);
99 return obj;
100 }
101
102 inline bool asBoolean(PyObject *obj) {
103 return PyObject_IsTrue(obj) != 0;
104 }
105
106 }
107
108 /*------------------------------
109 * Python defines
110 ------------------------------*/
111
112 /// some basic python macros
113 #define Py_NEWARGS 1
114 /// return with no return value if nothing happens
115 #define Py_Return return Py_INCREF(Py_None), Py_None
116 /// returns an error
117 #define Py_Error(E, M) _Py_Error(return(nullptr),E,M)
118 #define _Py_Error(R, E, M) {PyErr_SetString(E, M); R;}
119 /// returns an error
120 #define Py_ErrorObj(E, O) _Py_ErrorObj(return(nullptr),E,O)
121 #define _Py_ErrorObj(R, E, O) {PyErr_SetObject(E, O); R;}
122 /// checks on a condition and returns an error on failure
123 #define Py_Try(F) {if (!(F)) return NULL;}
124 /// assert which returns with an error on failure
125 #define Py_Assert(A,E,M) {if (!(A)) {PyErr_SetString(E, M); return nullptr;}}
126
127
128 /// This must be the first line of each PyC++ class
129 #define Py_Header \
130 public: \
131 static PyTypeObject Type; \
132 static PyMethodDef Methods[]; \
133 virtual PyTypeObject *GetType(void) const {return &Type;}
134
135 /*------------------------------
136 * PyObjectBase
137 ------------------------------*/
138
139 namespace Base
140 {
141
142
143 /** The PyObjectBase class, exports the class as a Python type
144 * PyObjectBase is the base class for all C++ classes which
145 * need to get exported into the Python namespace. This class is
146 * very important because nearly all important classes in FreeCAD
147 * are visible in Python for macro recording and automation purpose.
148 * The class App::Document is a good example for an exported class.
149 * There are some convenience macros to make it easier to inherit
150 * from this class and defining new methods exported to Python.
151 * PYFUNCDEF_D defines a new exported method.
152 * PYFUNCIMP_D defines the implementation of the new exported method.
153 * In the implementation you can use Py_Return, Py_Error, Py_Try and Py_Assert.
154 * PYMETHODEDEF makes the entry in the Python method table.
155 * @see Document
156 * @see PYFUNCDEF_D
157 * @see PYFUNCIMP_D
158 * @see PYMETHODEDEF
159 * @see Py_Return
160 * @see Py_Error
161 * @see Py_Try
162 * @see Py_Assert
163 */
164 class BaseExport PyObjectBase : public PyObject //NOLINT
165 {
166 /** Py_Header struct from python.h.
167 * Every PyObjectBase object is also a python object. So you can use
168 * every Python C-Library function also on a PyObjectBase object
169 */
170 Py_Header
171
172 enum Status {
173 Valid = 0,
174 Immutable = 1,
175 Notify = 2,
176 NoTrack = 3
177 };
178
179 protected:
180 /// destructor
181 virtual ~PyObjectBase();
182
183 /// Overrides the pointer to the twin object
184 void setTwinPointer(void* ptr) {
185 _pcTwinPointer = ptr;
186 }
187
188 public:
189 /** Constructor
190 * Sets the Type of the object (for inheritance) and decrease the
191 * the reference count of the PyObject.
192 */
193 PyObjectBase(void*, PyTypeObject *T);
194 /// Wrapper for the Python destructor
195 static void PyDestructor(PyObject *P) // python wrapper
196 { delete ((PyObjectBase *) P); }
197 /// incref method wrapper (see python extending manual)
198 PyObjectBase* IncRef() {Py_INCREF(this);return this;}
199 /// decref method wrapper (see python extending manual)
200 PyObjectBase* DecRef() {Py_DECREF(this);return this;}
201
202 /// Get the pointer of the twin object
203 void* getTwinPointer() const {
204 return _pcTwinPointer;
205 }
206
207 /** GetAttribute implementation
208 * This method implements the retrieval of object attributes.
209 * If you want to implement attributes in your class, reimplement
210 * this method.
211 * You have to call the method of the base class.
212 * Note: if you reimplement _gettattr() in a inheriting class you
213 * need to call the method of the base class! Otherwise even the
214 * methods of the object will disappear!
215 */
216 virtual PyObject *_getattr(const char *attr);
217 /// static wrapper for pythons _getattro()
218 static PyObject *__getattro(PyObject * PyObj, PyObject *attro);
219
220 /** SetAttribute implementation
221 * This method implements the setting of object attributes.
222 * If you want to implement attributes in your class, reimplement
223 * this method.
224 * You have to call the method of the base class.
225 */
226 virtual int _setattr(const char *attro, PyObject *value); // _setattr method
227 /// static wrapper for pythons _setattro(). // This should be the entry in Type.
228 static int __setattro(PyObject *PyObj, PyObject *attro, PyObject *value);
229
230 /** _repr method
231 * Override this method to return a string object with some
232 * information about the object.
233 * \code
234 * PyObject *MeshFeaturePy::_repr(void)
235 * {
236 * std::stringstream a;
237 * a << "MeshFeature: [ ";
238 * a << "some really important info about the object!";
239 * a << "]" << std::endl;
240 * return Py_BuildValue("s", a.str().c_str());
241 * }
242 * \endcode
243 */
244 virtual PyObject *_repr();
245 /// python wrapper for the _repr() function
246 static PyObject *__repr(PyObject *PyObj) {
247 if (!((PyObjectBase*) PyObj)->isValid()){
248 PyErr_Format(PyExc_ReferenceError, "Cannot print representation of deleted object");
249 return nullptr;
250 }
251 return ((PyObjectBase*) PyObj)->_repr();
252 }
253
254 /** PyInit method
255 * Override this method to initialize a newly created
256 * instance of the class (Constructor)
257 */
258 virtual int PyInit(PyObject* /*args*/, PyObject* /*kwd*/)
259 {
260 return 0;
261 }
262 /// python wrapper for the _repr() function
263 static int __PyInit(PyObject* self, PyObject* args, PyObject* kwd)
264 {
265 return ((PyObjectBase*) self)->PyInit(args, kwd);
266 }
267
268 void setInvalid() {
269 // first bit is not set, i.e. invalid
270 StatusBits.reset(Valid);
271 clearAttributes();
272 _pcTwinPointer = nullptr;
273 }
274
275 bool isValid() {
276 return StatusBits.test(Valid);
277 }
278
279 void setConst() {
280 // second bit is set, i.e. immutable
281 StatusBits.set(Immutable);
282 }
283
284 bool isConst() {
285 return StatusBits.test(Immutable);
286 }
287
288 void setShouldNotify(bool on) {
289 StatusBits.set(Notify, on);
290 }
291
292 bool shouldNotify() const {
293 return StatusBits.test(Notify);
294 }
295
296 void startNotify();
297
298 void setNotTracking(bool on=true) {
299 StatusBits.set(NoTrack, on);
300 }
301
302 bool isNotTracking() const {
303 return StatusBits.test(NoTrack);
304 }
305
306 using PointerType = void*;
307
308 private:
309 void setAttributeOf(const char* attr, PyObject* par);
310 void resetAttribute();
311 PyObject* getTrackedAttribute(const char* attr);
312 void trackAttribute(const char* attr, PyObject* obj);
313 void untrackAttribute(const char* attr);
314 void clearAttributes();
315
316 protected:
317 std::bitset<32> StatusBits; //NOLINT
318 /// pointer to the handled class
319 void * _pcTwinPointer; //NOLINT
320
321 public:
322 PyObject* baseProxy{nullptr}; //NOLINT
323
324 private:
325 PyObject* attrDict{nullptr};
326 };
327
328
329
330
331 /** Python dynamic class macro for definition
332 * sets up a static/dynamic function entry in a class inheriting
333 * from PyObjectBase. Its a pure convenience macro. You can also do
334 * it by hand if you want. It looks like that:
335 * \code
336 * PyObject *PyGetGrp(PyObject *args);
337 * static PyObject *sPyGetGrp(PyObject *self, PyObject *args, PyObject *kwd)
338 * {return ((FCPyParametrGrp*)self)->PyGetGrp(args);};
339 * \endcode
340 * first the method is defined which have the functionality then the
341 * static wrapper is used to provide a callback for python. The call
342 * is simply mapped to the method.
343 * @param CLASS is the class in which the macro take place.
344 * @param DFUNC is the object method get defined and called
345 * sDFUNC is the static method name (use what you want)
346 * @see PYFUNCIMP_D
347 * @see PyObjectBase
348 */
349 #define PYFUNCDEF_D(CLASS,DFUNC) PyObject * DFUNC (PyObject *args); \
350 static PyObject * s##DFUNC (PyObject *self, PyObject *args, PyObject * /*kwd*/){return (( CLASS *)self)-> DFUNC (args);};
351
352 /** Python dynamic class macro for implementation
353 * used to set up an implementation for PYFUNCDEF_D definition.
354 * Its a pure convenience macro. You can also do
355 * it by hand if you want. It looks like that:
356 * \code
357 * PyObject *FCPyParametrGrp::PyGetGrp(PyObject *args)
358 * \endcode
359 * see PYFUNCDEF_D for details * @param CLASS is the class in which the macro take place.
360 * @param DFUNC is the object method get defined and called
361 * @see PYFUNCDEF_D
362 * @see PyObjectBase
363 */
364 #define PYFUNCIMP_D(CLASS,DFUNC) PyObject* CLASS::DFUNC (PyObject *args)
365
366
367
368 /** Python dynamic class macro for the method list
369 * used to fill the method list of a class derived from PyObjectBase.
370 * Its a pure convenience macro. You can also do
371 * it by hand if you want. It looks like that:
372 * \code
373 * PyMethodDef DocTypeStdPy::Methods[] = {
374 * {"AddFeature", (PyCFunction) sAddFeature, Py_NEWARGS},
375 * {"RemoveFeature", (PyCFunction) sRemoveFeature, Py_NEWARGS},
376 * {NULL, NULL}
377 * };
378 * \endcode
379 * instead of:
380 * \code
381 * PyMethodDef DocTypeStdPy::Methods[] = {
382 * PYMETHODEDEF(AddFeature)
383 * PYMETHODEDEF(RemoveFeature)
384 * {NULL, NULL}
385 * };
386 * \endcode
387 * see PYFUNCDEF_D for details
388 * @param FUNC is the object method get defined
389 * @see PYFUNCDEF_D
390 * @see PyObjectBase
391 */
392 #define PYMETHODEDEF(FUNC) {"" #FUNC "",(PyCFunction) s##FUNC,Py_NEWARGS},
393
394 BaseExport extern PyObject* PyExc_FC_GeneralError;
395 #define PY_FCERROR (Base::PyExc_FC_GeneralError ? \
396 PyExc_FC_GeneralError : PyExc_RuntimeError)
397
398 BaseExport extern PyObject* PyExc_FC_FreeCADAbort;
399 BaseExport extern PyObject* PyExc_FC_XMLBaseException;
400 BaseExport extern PyObject* PyExc_FC_XMLParseException;
401 BaseExport extern PyObject* PyExc_FC_XMLAttributeError;
402 BaseExport extern PyObject* PyExc_FC_UnknownProgramOption;
403 BaseExport extern PyObject* PyExc_FC_BadFormatError;
404 BaseExport extern PyObject* PyExc_FC_BadGraphError;
405 BaseExport extern PyObject* PyExc_FC_ExpressionError;
406 BaseExport extern PyObject* PyExc_FC_ParserError;
407 BaseExport extern PyObject* PyExc_FC_CADKernelError;
408 BaseExport extern PyObject* PyExc_FC_PropertyError;
409 BaseExport extern PyObject* PyExc_FC_AbortIOException;
410
411 /** Exception handling for python callback functions
412 * Is a convenience macro to manage the exception handling of python callback
413 * functions defined in classes inheriting PyObjectBase and using PYMETHODEDEF .
414 * You can automate this:
415 * \code
416 * PYFUNCIMP_D(DocTypeStdPy,AddFeature)
417 * {
418 * char *pstr;
419 * if (!PyArg_ParseTuple(args, "s", &pstr))
420 * return nullptr;
421 *
422 * try {
423 * Feature *pcFtr = _pcDocTypeStd->AddFeature(pstr);
424 * }catch(...) \
425 * { \
426 * Py_Error(Base::PyExc_FC_GeneralError,"Unknown C++ exception"); \
427 * }catch(FCException e) ..... // and so on.... \
428 * }
429 * \endcode
430 * with that:
431 * \code
432 * PYFUNCIMP_D(DocTypeStdPy,AddFeature)
433 * {
434 * char *pstr;
435 * if (!PyArg_ParseTuple(args, "s", &pstr))
436 * return nullptr;
437 *
438 * PY_TRY {
439 * Feature *pcFtr = _pcDocTypeStd->AddFeature(pstr);
440 * }PY_CATCH;
441 * }
442 * \endcode
443 * this catch maps all of the FreeCAD standard exception to a clear output for the
444 * Python exception.
445 * @see PYMETHODEDEF
446 * @see PyObjectBase
447 */
448 #define PY_TRY try
449
450 #define __PY_CATCH(R) \
451 catch(const Base::Exception &e) \
452 { \
453 e.setPyException(); \
454 R; \
455 } \
456 catch(const std::exception &e) \
457 { \
458 _Py_Error(R,Base::PyExc_FC_GeneralError, e.what()); \
459 } \
460 catch(const Py::Exception&) \
461 { \
462 R; \
463 } \
464
465 #ifndef DONT_CATCH_CXX_EXCEPTIONS
466 /// see docu of PY_TRY
467 # define _PY_CATCH(R) \
468 __PY_CATCH(R) \
469 catch(...) \
470 { \
471 _Py_Error(R,Base::PyExc_FC_GeneralError,"Unknown C++ exception"); \
472 }
473
474 #else
475 /// see docu of PY_TRY
476 # define _PY_CATCH(R) __PY_CATCH(R)
477 #endif // DONT_CATCH_CXX_EXCEPTIONS
478
479 #define PY_CATCH _PY_CATCH(return(nullptr))
480
481 /** Python helper class
482 * This class encapsulate the Decoding of UTF8 to a python object.
483 * Including exception handling.
484 */
485 inline PyObject * PyAsUnicodeObject(const char *str)
486 {
487 // Returns a new reference, don't increment it!
488 Py_ssize_t len = Py_SAFE_DOWNCAST(strlen(str), size_t, Py_ssize_t);
489 PyObject *p = PyUnicode_DecodeUTF8(str, len, nullptr);
490 if (!p) {
491 throw Base::UnicodeError("UTF8 conversion failure at PyAsUnicodeString()");
492 }
493 return p;
494 }
495
496 inline PyObject * PyAsUnicodeObject(const std::string &str)
497 {
498 return PyAsUnicodeObject(str.c_str());
499 }
500
501 /** Helper functions to check if a python object is of a specific type or None,
502 * otherwise raise an exception.
503 * If the object is None, the pointer is set to nullptr.
504 */
505 inline void PyTypeCheck(PyObject** ptr, PyTypeObject* type, const char* msg=nullptr)
506 {
507 if (*ptr == Py_None) {
508 *ptr = nullptr;
509 return;
510 }
511 if (!PyObject_TypeCheck(*ptr, type)) {
512 if (!msg) {
513 std::stringstream str;
514 str << "Type must be " << type->tp_name << " or None, not " << (*ptr)->ob_type->tp_name;
515 throw Base::TypeError(str.str());
516 }
517 throw Base::TypeError(msg);
518 }
519 }
520
521 inline void PyTypeCheck(PyObject** ptr, int (*method)(PyObject*), const char* msg)
522 {
523 if (*ptr == Py_None) {
524 *ptr = nullptr;
525 return;
526 }
527 if (!method(*ptr)) {
528 throw Base::TypeError(msg);
529 }
530 }
531
532 /**
533 * @brief Registers a C++ enum as a Python IntEnum in the specified module.
534 *
535 * This function dynamically creates a Python `IntEnum` class using the provided
536 * C++ enum entries and registers it under the given name within the specified
537 * Python module. It allows seamless integration of C++ enums into Python, making
538 * them accessible and usable in Python scripts.
539 *
540 * @tparam T The type of the enum values.
541 * @param module The Python module where the enum will be registered.
542 * @param name The name to be given to the Python IntEnum.
543 * @param entries A map of string keys to enum values, representing the enum definition.
544 */
545 template <typename T>
546 void PyRegisterEnum(PyObject* module, const char* name, const std::map<const char*, T>& entries)
547 {
548 PyObject* pyEnumModule = PyImport_ImportModule("enum");
549 if (!pyEnumModule) {
550 return;
551 }
552
553 PyObject* pyConstantsDict = PyDict_New();
554
555 // Populate dictionary
556 for (const auto& [key, value] : entries) {
557 PyDict_SetItemString(pyConstantsDict, key, PyLong_FromLong(static_cast<int>(value)));
558 }
559
560 PyObject* pyEnumClass = PyObject_CallMethod(pyEnumModule, "IntEnum", "sO", name, pyConstantsDict);
561
562 Py_CLEAR(pyConstantsDict);
563 Py_CLEAR(pyEnumModule);
564
565 if (pyEnumClass && PyModule_AddObject(module, name, pyEnumClass) < 0) {
566 Py_CLEAR(pyEnumClass);
567 }
568 }
569
570
571 } // namespace Base
572
573 // NOLINTEND(cppcoreguidelines-macro-usage)
574 // clang-format on
575
576 #endif // BASE_PYOBJECTBASE_H