Blender V5.3
bpy_rna.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
14
15#include <Python.h>
16
17#include <cfloat> /* FLT_MIN/MAX */
18#include <cstddef>
19#include <optional>
20
21#include "DNA_listBase.h"
22#include "RNA_path.hh"
23#include "RNA_types.hh"
24
25#include "BLI_alloca.hh"
26#include "BLI_dynstr.hh"
27#include "BLI_listbase.hh"
29#include "BLI_path_utils.hh"
30#include "BLI_string.hh"
31#include "BLI_string_utf8.hh"
32#include "BLI_utildefines.hh"
33#include "BLI_vector.hh"
34
35#include "BPY_extern.hh"
36#include "BPY_extern_clog.hh"
37
38#include "bpy_capi_utils.hh"
39#include "bpy_intern_string.hh"
40#include "bpy_props.hh"
41#include "bpy_rna.hh"
42#include "bpy_rna_anim.hh"
43#include "bpy_rna_callback.hh"
44
45#ifdef USE_PYRNA_INVALIDATE_WEAKREF
46# include "BLI_ghash.hh"
47#endif
48
49#include "RNA_access.hh"
50#include "RNA_define.hh" /* RNA_def_property_free_identifier */
51#include "RNA_enum_types.hh"
52#include "RNA_prototypes.hh"
53
54#include "CLG_log.h"
55
56#include "MEM_guardedalloc.h"
57
59
60#include "BKE_context.hh"
61#include "BKE_global.hh" /* evil G.* */
62#include "BKE_idprop.hh"
63#include "BKE_idtype.hh"
64#include "BKE_main.hh"
65#include "BKE_report.hh"
66
67/* Only for types. */
68#include "BKE_node.hh"
69
71
72#include "../generic/idprop_py_api.hh" /* For IDprop lookups. */
76#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
78
79namespace blender {
80
81#define USE_PEDANTIC_WRITE
82#define USE_MATHUTILS
83#define USE_STRING_COERCE
84
92#define USE_POSTPONED_ANNOTATIONS
93
94/* Unfortunately Python needs to hold a global reference to the context.
95 * If we remove this is means `bpy.context` won't be usable from some parts of the code:
96 * `bpy.app.handler` callbacks for example.
97 * Even though this is arguably "correct", it's going to cause problems for existing scripts,
98 * so accept having this for the time being. */
99
100BPy_StructRNA *bpy_context_module = nullptr; /* for fast access */
101
106static const char *BPy_capsule_PointerRNA_identifier = "BPy_PointerRNA_PyCapsule";
107
113
118static const char *BPy_PropertyPointerRNA_capsule_identifier = "BPy_PropertyPointerRNA_PyCapsule";
119
123static PyObject *pyrna_func_CreatePyObject(const PointerRNA *ptr, FunctionRNA *func);
124
125static PyObject *pyrna_struct_CreatePyObject_from_type(const PointerRNA *ptr,
126 PyTypeObject *tp,
127 void **instance);
128
129static PyObject *pyrna_srna_Subtype(StructRNA *srna);
130static PyObject *pyrna_struct_Subtype(PointerRNA *ptr);
131static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
132
133static PyObject *pyrna_register_class(PyObject *self, PyObject *py_class);
134static PyObject *pyrna_unregister_class(PyObject *self, PyObject *py_class);
135
137
138/* -------------------------------------------------------------------- */
143
153static PyObject *pyweakref_get_ref(PyObject *ref)
154{
155 PyObject *result = nullptr;
156 if (PyWeakref_GetRef(ref, &result) == -1) [[unlikely]] {
157 /* This hints at a bug, it's not expected so being noisy is OK. */
158 CLOG_WARN(BPY_LOG_RNA, "unexpected error accessing weak-reference");
159 /* Prints and clears the error. */
160 PyErr_Print();
161 }
162 return result;
163}
164
166
171#define BPY_DOC_ID_PROP_TYPE_NOTE \
172 " .. note::\n" \
173 "\n" \
174 " Limited to: :ref:`bpy_types-custom_properties`.\n"
175
177{
178 if (pysrna->ptr->has_type()) {
179 return 0;
180 }
181 return -1;
182}
183
185{
186 PyErr_Format(
187 PyExc_ReferenceError, "StructRNA of type %.200s has been removed", Py_TYPE(pysrna)->tp_name);
188}
189
191{
192 if (pysrna->ptr->has_type()) {
193 return 0;
194 }
196 return -1;
197}
198
200{
201 if (self->ptr->has_type()) {
202 return 0;
203 }
204 PyErr_Format(PyExc_ReferenceError,
205 "PropertyRNA of type %.200s.%.200s has been removed",
206 Py_TYPE(self)->tp_name,
208 return -1;
209}
210
212{
213 self->ptr->invalidate();
214}
215
217 const PropertyRNA *prop,
218 const DeprecatedRNA *deprecated)
219{
220 PyErr_WarnFormat(PyExc_DeprecationWarning,
221 1,
222 "'%s.%s' is expected to be removed in Blender %d.%d",
225 deprecated->removal_version / 100,
226 deprecated->removal_version % 100,
227 deprecated->note);
228}
229
230static bool pyrna_status_ok_or_error(eRNAStatus status, const char *error_prefix)
231{
232 switch (status) {
233 case eRNAStatus::Success: {
234 return true;
235 }
237 PyErr_Format(PyExc_IndexError, "%.200s: index out of range", error_prefix);
238 return false;
239 }
241 PyErr_Format(PyExc_TypeError, "%.200s: is not editable", error_prefix);
242 return false;
243 }
245 PyErr_Format(PyExc_TypeError, "%.200s: not supported for this collection", error_prefix);
246 return false;
247 }
248 }
249
251 return true;
252}
253
254#ifdef USE_PYRNA_INVALIDATE_GC
255# define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g) + 1))
256
257/* Only for sizeof(). */
258struct gc_generation {
259 PyGC_Head head;
260 int threshold;
261 int count;
262} gc_generation;
263
264static void id_release_gc(struct ID *id)
265{
266 uint j;
267 // uint i = 0;
268 for (j = 0; j < 3; j++) {
269 /* Hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed. */
270 PyGC_Head *gen = (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
271 PyGC_Head *g = gen->gc.gc_next;
272 while ((g = g->gc.gc_next) != gen) {
273 PyObject *ob = FROM_GC(g);
274 if (PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) ||
275 PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type))
276 {
278 if (ob_ptr->ptr->owner_id == id) {
279 pyrna_invalidate(ob_ptr);
280 // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
281 // i++;
282 }
283 }
284 }
285 }
286 // printf("id_release_gc freed '%s': %d\n", id->name, i);
287}
288#endif
289
290#ifdef USE_PYRNA_INVALIDATE_WEAKREF
291// #define DEBUG_RNA_WEAKREF
292
293struct GHash *id_weakref_pool = nullptr;
294static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref);
295static PyMethodDef id_free_weakref_cb_def = {
296 "id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, nullptr};
297
301static void id_weakref_pool_free_value_fn(void *p)
302{
303 GHash *weakinfo_hash = static_cast<GHash *>(p);
304 BLI_ghash_free(weakinfo_hash, nullptr, nullptr);
305}
306
307/* Adds a reference to the list, remember to decref. */
308static GHash *id_weakref_pool_get(ID *id)
309{
310 GHash *weakinfo_hash = static_cast<GHash *>(BLI_ghash_lookup(id_weakref_pool, (void *)id));
311 if (weakinfo_hash == nullptr) {
312 /* This could be a set, values are used to keep a reference back to the ID
313 * (all of them are the same). */
314 weakinfo_hash = BLI_ghash_ptr_new("rna_id");
315 BLI_ghash_insert(id_weakref_pool, id, weakinfo_hash);
316 }
317 return weakinfo_hash;
318}
319
320/* Called from pyrna_struct_CreatePyObject() and pyrna_prop_CreatePyObject(). */
321static void id_weakref_pool_add(ID *id, BPy_DummyPointerRNA *pyrna)
322{
323 PyObject *weakref;
324 PyObject *weakref_capsule;
325 PyObject *weakref_cb_py;
326
327 /* Create a new function instance and insert the list as 'self'
328 * so we can remove ourself from it. */
329 GHash *weakinfo_hash = id_weakref_pool_get(id); /* New or existing. */
330
331 weakref_capsule = PyCapsule_New(weakinfo_hash, nullptr, nullptr);
332 weakref_cb_py = PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
333 Py_DECREF(weakref_capsule);
334
335 /* Add weakref to weakinfo_hash list. */
336 weakref = PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
337
338 Py_DECREF(weakref_cb_py); /* Function owned by the weakref now. */
339
340 /* Important to add at the end of the hash, since first removal looks at the end. */
341
342 /* Using a hash table as a set, all 'id's are the same. */
343 BLI_ghash_insert(weakinfo_hash, weakref, id);
344 /* weakinfo_hash owns the weakref */
345}
346
347/* Workaround to get the last id without a lookup. */
348static ID *_id_tmp_ptr;
349static void value_id_set(void *id)
350{
351 _id_tmp_ptr = (ID *)id;
352}
353
354static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash);
355static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref)
356{
357 /* Important to search backwards. */
358 GHash *weakinfo_hash = static_cast<GHash *>(PyCapsule_GetPointer(weakinfo_pair, nullptr));
359
360 if (BLI_ghash_len(weakinfo_hash) > 1) {
361 BLI_ghash_remove(weakinfo_hash, weakref, nullptr, nullptr);
362 }
363 else { /* Get the last id and free it. */
364 BLI_ghash_remove(weakinfo_hash, weakref, nullptr, value_id_set);
365 id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
366 }
367
368 Py_DECREF(weakref);
369
370 Py_RETURN_NONE;
371}
372
373static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
374{
375 GHashIterator weakinfo_hash_iter;
376
377 BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
378
379# ifdef DEBUG_RNA_WEAKREF
380 fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_len(weakinfo_hash));
381# endif
382
383 while (!BLI_ghashIterator_done(&weakinfo_hash_iter)) {
384 PyObject *weakref = (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
385 PyObject *item = pyweakref_get_ref(weakref);
386 if (item) {
387# ifdef DEBUG_RNA_WEAKREF
388 PyC_ObSpit("id_release_weakref item ", item);
389# endif
391 Py_DECREF(item);
392 }
393
394 Py_DECREF(weakref);
395
396 BLI_ghashIterator_step(&weakinfo_hash_iter);
397 }
398
399 BLI_ghash_remove(id_weakref_pool, (void *)id, nullptr, nullptr);
400 BLI_ghash_free(weakinfo_hash, nullptr, nullptr);
401}
402
403static void id_release_weakref(struct ID *id)
404{
405 GHash *weakinfo_hash = static_cast<GHash *>(BLI_ghash_lookup(id_weakref_pool, (void *)id));
406 if (weakinfo_hash) {
407 id_release_weakref_list(id, weakinfo_hash);
408 }
409}
410
411#endif /* USE_PYRNA_INVALIDATE_WEAKREF */
412
414 PyObject *(*nameprop_as_py_object_fn)(const char *, Py_ssize_t);
416};
417
422 PointerRNA *ptr, BPy_NamePropAsPyObject_Cache &nameprop_cache)
423{
424 char fixedbuf[256];
425 int name_len;
426 PropertyRNA *nameprop;
427 char *name_ptr = RNA_struct_name_get_alloc_ex(
428 ptr, fixedbuf, sizeof(fixedbuf), &name_len, &nameprop);
429 if (name_ptr) [[likely]] {
430 /* In most cases this only runs once. */
431 if (nameprop != nameprop_cache.nameprop) [[unlikely]] {
432 nameprop_cache.nameprop = nameprop;
433 const PropertySubType subtype = RNA_property_subtype(nameprop);
436 }
437 else {
438 nameprop_cache.nameprop_as_py_object_fn = PyUnicode_FromStringAndSize;
439 }
440 }
441 PyObject *result = nameprop_cache.nameprop_as_py_object_fn(name_ptr, name_len);
442 /* The string data may be corrupt if this asserts,
443 * or not using a file-path sub-type when it should.. */
444 BLI_assert(result != nullptr);
445 if (name_ptr != fixedbuf) {
446 MEM_delete(name_ptr);
447 }
448 return result;
449 }
450 return nullptr;
451}
452
454{
455#ifdef USE_PYRNA_INVALIDATE_GC
456 id_release_gc(id);
457#endif
458
459#ifdef USE_PYRNA_INVALIDATE_WEAKREF
460 /* Check for nullptr since this may run before Python has been started. */
461 if (id_weakref_pool != nullptr) {
462 PyGILState_STATE gilstate = PyGILState_Ensure();
463
464 id_release_weakref(id);
465
466 PyGILState_Release(gilstate);
467 }
468#endif /* USE_PYRNA_INVALIDATE_WEAKREF */
469
470 (void)id;
471}
472
473#ifdef USE_PEDANTIC_WRITE
474/* Thread local as e.g. Python handlers in the render thread should not be
475 * affected by Python UI drawing method in the main thread. */
476static thread_local bool rna_disallow_writes = false;
477
478static bool rna_id_write_error(PointerRNA *ptr, PyObject *key)
479{
480 ID *id = ptr->owner_id;
481 if (id) {
482 const short idcode = id->id_type();
483 /* May need more ID types added here. */
484 if (!ELEM(idcode, ID_WM, ID_SCR, ID_WS)) {
485 const char *idtype = BKE_idtype_idcode_to_name(idcode);
486 const char *pyname;
487 if (key && PyUnicode_Check(key)) {
488 pyname = PyUnicode_AsUTF8(key);
489 }
490 else {
491 pyname = "<UNKNOWN>";
492 }
493
494 /* Make a nice string error. */
495 BLI_assert(idtype != nullptr);
496 PyErr_Format(PyExc_AttributeError,
497 "Writing to ID classes in this context is not allowed: "
498 "%.200s, %.200s data-block, error setting %.200s.%.200s",
499 id->name + 2,
500 idtype,
502 pyname);
503
504 return true;
505 }
506 }
507 return false;
508}
509#endif /* USE_PEDANTIC_WRITE */
510
511#ifdef USE_PEDANTIC_WRITE
512
513/* NOTE: Without the GIL, this can cause problems when called from threads, see: #127767. */
514
516{
517 BLI_assert(PyGILState_Check());
518
519 return !rna_disallow_writes;
520}
521
522void pyrna_write_set(bool val)
523{
524 BLI_assert(PyGILState_Check());
525
526 rna_disallow_writes = !val;
527}
528
533
538#else /* USE_PEDANTIC_WRITE */
540{
541 BLI_assert(PyGILState_Check());
542
543 return true;
544}
545void pyrna_write_set(bool /*val*/)
546{
547 BLI_assert(PyGILState_Check());
548
549 /* pass */
550}
551void pyrna_context_init(bContext * /*C*/) {}
552void pyrna_context_clear(bContext * /*C*/) {}
553#endif /* USE_PEDANTIC_WRITE */
554
555static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
556static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
557static int pyrna_py_to_prop(PointerRNA *ptr,
558 PropertyRNA *prop,
559 void *data,
560 PyObject *value,
561 const char *error_prefix,
562 PyObject **r_value_coerce);
563static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
564
565} // namespace blender
566
567#ifdef USE_MATHUTILS
568# include "../mathutils/mathutils.hh" /* So we can have mathutils callbacks. */
569
570namespace blender {
571
573 PointerRNA *ptr,
574 PropertyRNA *prop,
575 Py_ssize_t start,
576 Py_ssize_t step,
577 Py_ssize_t slice_length,
578 Py_ssize_t array_length);
580 const short order_fallback,
581 PropertyRNA **r_prop_eul_order);
582
583/* `bpyrna` vector/euler/quaternion callbacks. */
584static uchar mathutils_rna_array_cb_index = -1; /* Index for our callbacks. */
585
586/* Sub-type not used much yet. */
587# define MATHUTILS_CB_SUBTYPE_EUL 0
588# define MATHUTILS_CB_SUBTYPE_VEC 1
589# define MATHUTILS_CB_SUBTYPE_QUAT 2
590# define MATHUTILS_CB_SUBTYPE_COLOR 3
591
593{
594 BPy_PropertyRNA *self = reinterpret_cast<BPy_PropertyRNA *>(bmo->cb_user);
595
597
598 return self->prop ? 0 : -1;
599}
600
601static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
602{
603 BPy_PropertyRNA *self = reinterpret_cast<BPy_PropertyRNA *>(bmo->cb_user);
604
606
607 if (self->prop == nullptr) {
608 return -1;
609 }
610
611 RNA_property_float_get_array(&self->ptr.value(), self->prop, bmo->data);
612
613 /* Euler order exception. */
614 if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
615 EulerObject *eul = reinterpret_cast<EulerObject *>(bmo);
616 PropertyRNA *prop_eul_order = nullptr;
617 eul->order = pyrna_rotation_euler_order_get(&self->ptr.value(), eul->order, &prop_eul_order);
618 }
619
620 return 0;
621}
622
623static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
624{
625 BPy_PropertyRNA *self = reinterpret_cast<BPy_PropertyRNA *>(bmo->cb_user);
626 float min, max;
627
629
630 if (self->prop == nullptr) {
631 return -1;
632 }
633
634# ifdef USE_PEDANTIC_WRITE
635 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), nullptr)) {
636 return -1;
637 }
638# endif /* USE_PEDANTIC_WRITE */
639
640 if (!RNA_property_editable_flag(&self->ptr.value(), self->prop)) {
641 PyErr_Format(PyExc_AttributeError,
642 "bpy_prop \"%.200s.%.200s\" is read-only",
643 RNA_struct_identifier(self->ptr->type),
645 return -1;
646 }
647
648 RNA_property_float_range(&self->ptr.value(), self->prop, &min, &max);
649
650 if (min != -FLT_MAX || max != FLT_MAX) {
651 int i, len = RNA_property_array_length(&self->ptr.value(), self->prop);
652 for (i = 0; i < len; i++) {
653 CLAMP(bmo->data[i], min, max);
654 }
655 }
656
657 RNA_property_float_set_array(&self->ptr.value(), self->prop, bmo->data);
658 if (RNA_property_update_check(self->prop)) {
659 RNA_property_update(BPY_context_get(), &self->ptr.value(), self->prop);
660 }
661
662 /* Euler order exception. */
663 if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
664 EulerObject *eul = reinterpret_cast<EulerObject *>(bmo);
665 PropertyRNA *prop_eul_order = nullptr;
666 const short order = pyrna_rotation_euler_order_get(
667 &self->ptr.value(), eul->order, &prop_eul_order);
668 if (order != eul->order) {
669 RNA_property_enum_set(&self->ptr.value(), prop_eul_order, eul->order);
670 if (RNA_property_update_check(prop_eul_order)) {
671 RNA_property_update(BPY_context_get(), &self->ptr.value(), prop_eul_order);
672 }
673 }
674 }
675 return 0;
676}
677
678static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int /*subtype*/, int index)
679{
680 BPy_PropertyRNA *self = reinterpret_cast<BPy_PropertyRNA *>(bmo->cb_user);
681
683
684 if (self->prop == nullptr) {
685 return -1;
686 }
687
688 bmo->data[index] = RNA_property_float_get_index(&self->ptr.value(), self->prop, index);
689 return 0;
690}
691
692static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int /*subtype*/, int index)
693{
694 BPy_PropertyRNA *self = reinterpret_cast<BPy_PropertyRNA *>(bmo->cb_user);
695
697
698 if (self->prop == nullptr) {
699 return -1;
700 }
701
702# ifdef USE_PEDANTIC_WRITE
703 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), nullptr)) {
704 return -1;
705 }
706# endif /* USE_PEDANTIC_WRITE */
707
708 if (!RNA_property_editable_flag(&self->ptr.value(), self->prop)) {
709 PyErr_Format(PyExc_AttributeError,
710 "bpy_prop \"%.200s.%.200s\" is read-only",
711 RNA_struct_identifier(self->ptr->type),
713 return -1;
714 }
715
716 RNA_property_float_clamp(&self->ptr.value(), self->prop, &bmo->data[index]);
717 RNA_property_float_set_index(&self->ptr.value(), self->prop, index, bmo->data[index]);
718
719 if (RNA_property_update_check(self->prop)) {
720 RNA_property_update(BPY_context_get(), &self->ptr.value(), self->prop);
721 }
722
723 return 0;
724}
725
733
734/* BPY/RNA matrix callbacks. */
735static uchar mathutils_rna_matrix_cb_index = -1; /* Index for our callbacks. */
736
737static int mathutils_rna_matrix_get(BaseMathObject *bmo, int /*subtype*/)
738{
739 BPy_PropertyRNA *self = reinterpret_cast<BPy_PropertyRNA *>(bmo->cb_user);
740
742
743 if (self->prop == nullptr) {
744 return -1;
745 }
746
747 RNA_property_float_get_array(&self->ptr.value(), self->prop, bmo->data);
748 return 0;
749}
750
751static int mathutils_rna_matrix_set(BaseMathObject *bmo, int /*subtype*/)
752{
753 BPy_PropertyRNA *self = reinterpret_cast<BPy_PropertyRNA *>(bmo->cb_user);
754
756
757 if (self->prop == nullptr) {
758 return -1;
759 }
760
761# ifdef USE_PEDANTIC_WRITE
762 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), nullptr)) {
763 return -1;
764 }
765# endif /* USE_PEDANTIC_WRITE */
766
767 if (!RNA_property_editable_flag(&self->ptr.value(), self->prop)) {
768 PyErr_Format(PyExc_AttributeError,
769 "bpy_prop \"%.200s.%.200s\" is read-only",
770 RNA_struct_identifier(self->ptr->type),
772 return -1;
773 }
774
775 /* Can ignore clamping here. */
776 RNA_property_float_set_array(&self->ptr.value(), self->prop, bmo->data);
777
778 if (RNA_property_update_check(self->prop)) {
779 RNA_property_update(BPY_context_get(), &self->ptr.value(), self->prop);
780 }
781 return 0;
782}
783
791
793 const short order_fallback,
794 PropertyRNA **r_prop_eul_order)
795{
796 /* Attempt to get order. */
797 if (*r_prop_eul_order == nullptr) {
798 *r_prop_eul_order = RNA_struct_find_property(ptr, "rotation_mode");
799 }
800
801 if (*r_prop_eul_order) {
802 const short order = RNA_property_enum_get(ptr, *r_prop_eul_order);
803 /* Could be quaternion or axis-angle. */
804 if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) {
805 return order;
806 }
807 }
808
809 return order_fallback;
810}
811
812#endif /* USE_MATHUTILS */
813
818#define PROP_ALL_VECTOR_SUBTYPES \
819 PROP_COORDS: \
820 case PROP_TRANSLATION: \
821 case PROP_DIRECTION: \
822 case PROP_VELOCITY: \
823 case PROP_ACCELERATION: \
824 case PROP_XYZ: \
825 case PROP_XYZ_LENGTH
826
828{
829 PyObject *ret = nullptr;
830
831#ifdef USE_MATHUTILS
832 int subtype, totdim;
833 int len;
834 const int flag = RNA_property_flag(prop);
835 const int type = RNA_property_type(prop);
836 const bool is_thick = (flag & PROP_THICK_WRAP) != 0;
837
838 /* disallow dynamic sized arrays to be wrapped since the size could change
839 * to a size mathutils does not support */
840 if (flag & PROP_DYNAMIC) {
841 return nullptr;
842 }
843
844 len = RNA_property_array_length(ptr, prop);
845 if (type == PROP_FLOAT) {
846 /* pass */
847 }
848 else if (type == PROP_INT) {
849 if (is_thick) {
850 goto thick_wrap_slice;
851 }
852 else {
853 return nullptr;
854 }
855 }
856 else {
857 return nullptr;
858 }
859
860 subtype = RNA_property_subtype(prop);
861 totdim = RNA_property_array_dimension(ptr, prop, nullptr);
862
863 if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
864 if (!is_thick) {
865 /* Owned by the mathutils PyObject. */
866 ret = pyrna_prop_CreatePyObject(ptr, prop);
867 }
868
869 switch (subtype) {
871 if (len >= 2 && len <= 4) {
872 if (is_thick) {
873 ret = Vector_CreatePyObject(nullptr, len, nullptr);
874 RNA_property_float_get_array(ptr, prop, (reinterpret_cast<VectorObject *>(ret))->vec);
875 }
876 else {
877 PyObject *vec_cb = Vector_CreatePyObject_cb(
879 Py_DECREF(ret); /* The vector owns 'ret' now. */
880 ret = vec_cb; /* Return the vector instead. */
881 }
882 }
883 break;
884 case PROP_MATRIX:
885 if (len == 16) {
886 if (is_thick) {
887 ret = Matrix_CreatePyObject(nullptr, 4, 4, nullptr);
889 ptr, prop, (reinterpret_cast<MatrixObject *>(ret))->matrix);
890 }
891 else {
892 PyObject *mat_cb = Matrix_CreatePyObject_cb(
894 Py_DECREF(ret); /* The matrix owns 'ret' now. */
895 ret = mat_cb; /* Return the matrix instead. */
896 }
897 }
898 else if (len == 9) {
899 if (is_thick) {
900 ret = Matrix_CreatePyObject(nullptr, 3, 3, nullptr);
902 ptr, prop, (reinterpret_cast<MatrixObject *>(ret))->matrix);
903 }
904 else {
905 PyObject *mat_cb = Matrix_CreatePyObject_cb(
907 Py_DECREF(ret); /* The matrix owns 'ret' now. */
908 ret = mat_cb; /* Return the matrix instead. */
909 }
910 }
911 break;
912 case PROP_EULER:
913 case PROP_QUATERNION:
914 if (len == 3) { /* Euler. */
915 if (is_thick) {
916 /* Attempt to get order,
917 * only needed for thick types since wrapped with update via callbacks. */
918 PropertyRNA *prop_eul_order = nullptr;
919 const short order = pyrna_rotation_euler_order_get(
920 ptr, EULER_ORDER_XYZ, &prop_eul_order);
921
922 ret = Euler_CreatePyObject(nullptr, order, nullptr); /* TODO: get order from RNA. */
923 RNA_property_float_get_array(ptr, prop, (reinterpret_cast<EulerObject *>(ret))->eul);
924 }
925 else {
926 /* Order will be updated from callback on use. */
927 /* TODO: get order from RNA. */
928 PyObject *eul_cb = Euler_CreatePyObject_cb(
930 Py_DECREF(ret); /* The euler owns 'ret' now. */
931 ret = eul_cb; /* Return the euler instead. */
932 }
933 }
934 else if (len == 4) {
935 if (is_thick) {
936 ret = Quaternion_CreatePyObject(nullptr, nullptr);
938 ptr, prop, (reinterpret_cast<QuaternionObject *>(ret))->quat);
939 }
940 else {
941 PyObject *quat_cb = Quaternion_CreatePyObject_cb(
943 Py_DECREF(ret); /* The quat owns 'ret' now. */
944 ret = quat_cb; /* Return the quat instead. */
945 }
946 }
947 break;
948 case PROP_COLOR:
949 case PROP_COLOR_GAMMA:
950 if (len == 3) { /* Color. */
951 if (is_thick) {
952 ret = Color_CreatePyObject(nullptr, nullptr);
953 RNA_property_float_get_array(ptr, prop, (reinterpret_cast<ColorObject *>(ret))->col);
954 }
955 else {
956 PyObject *col_cb = Color_CreatePyObject_cb(
958 Py_DECREF(ret); /* The color owns 'ret' now. */
959 ret = col_cb; /* Return the color instead. */
960 }
961 }
962 break;
963 default:
964 break;
965 }
966 }
967
968 if (ret == nullptr) {
969 if (is_thick) {
970 /* This is an array we can't reference (since it is not thin wrappable)
971 * and cannot be coerced into a mathutils type, so return as a list. */
972 thick_wrap_slice:
973 ret = pyrna_prop_array_subscript_slice(nullptr, ptr, prop, 0, 1, len, len);
974 }
975 else {
976 ret = pyrna_prop_CreatePyObject(ptr, prop); /* Owned by the mathutils PyObject. */
977 }
978 }
979#else /* USE_MATHUTILS */
980 (void)ptr;
981 (void)prop;
982#endif /* USE_MATHUTILS */
983
984 return ret;
985}
986
987/* NOTE(@ideasman42): Regarding comparison `__cmp__`:
988 * checking the 'ptr->data' matches works in almost all cases,
989 * however there are a few RNA properties that are fake sub-structs and
990 * share the pointer with the parent, in those cases this happens 'a.b == a'
991 * see: r43352 for example.
992 *
993 * So compare the 'ptr->type' as well to avoid this problem.
994 * It's highly unlikely this would happen that 'ptr->data' and 'ptr->prop' would match,
995 * but _not_ 'ptr->type' but include this check for completeness. */
996
998{
999 return (((a->ptr->data == b->ptr->data) && (a->ptr->type == b->ptr->type)) ? 0 : -1);
1000}
1001
1003{
1004 return (
1005 ((a->prop == b->prop) && (a->ptr->data == b->ptr->data) && (a->ptr->type == b->ptr->type)) ?
1006 0 :
1007 -1);
1008}
1009
1010static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
1011{
1012 PyObject *res;
1013 int ok = -1; /* Zero is true. */
1014
1016 ok = pyrna_struct_compare(reinterpret_cast<BPy_StructRNA *>(a),
1017 reinterpret_cast<BPy_StructRNA *>(b));
1018 }
1019
1020 switch (op) {
1021 case Py_NE:
1022 ok = !ok;
1024 case Py_EQ:
1025 res = ok ? Py_False : Py_True;
1026 break;
1027
1028 case Py_LT:
1029 case Py_LE:
1030 case Py_GT:
1031 case Py_GE:
1032 res = Py_NotImplemented;
1033 break;
1034 default:
1035 PyErr_BadArgument();
1036 return nullptr;
1037 }
1038
1039 return Py_NewRef(res);
1040}
1041
1042static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
1043{
1044 PyObject *res;
1045 int ok = -1; /* Zero is true. */
1046
1048 ok = pyrna_prop_compare(reinterpret_cast<BPy_PropertyRNA *>(a),
1049 reinterpret_cast<BPy_PropertyRNA *>(b));
1050 }
1051
1052 switch (op) {
1053 case Py_NE:
1054 ok = !ok;
1056 case Py_EQ:
1057 res = ok ? Py_False : Py_True;
1058 break;
1059
1060 case Py_LT:
1061 case Py_LE:
1062 case Py_GT:
1063 case Py_GE:
1064 res = Py_NotImplemented;
1065 break;
1066 default:
1067 PyErr_BadArgument();
1068 return nullptr;
1069 }
1070
1071 return Py_NewRef(res);
1072}
1073
1074/*----------------------repr--------------------------------------------*/
1075static PyObject *pyrna_struct_str(BPy_StructRNA *self)
1076{
1077 PyObject *ret;
1078 const char *name;
1079 const char *extra_info = "";
1080
1081 if (!PYRNA_STRUCT_IS_VALID(self)) {
1082 return PyUnicode_FromFormat("<bpy_struct, %.200s invalid>", Py_TYPE(self)->tp_name);
1083 }
1084
1085 ID *id = self->ptr->owner_id;
1086 if (id && id != DEG_get_original(id)) {
1087 extra_info = ", evaluated";
1088 }
1089
1090 /* Print name if available.
1091 *
1092 * Always include the pointer address since it can help identify unique data,
1093 * or when data is re-allocated internally. */
1094 name = RNA_struct_name_get_alloc(&self->ptr.value(), nullptr, 0, nullptr);
1095 if (name) {
1096 ret = PyUnicode_FromFormat("<bpy_struct, %.200s(\"%.200s\") at %p%s>",
1097 RNA_struct_identifier(self->ptr->type),
1098 name,
1099 self->ptr->data,
1100 extra_info);
1101 MEM_delete(name);
1102 return ret;
1103 }
1104
1105 return PyUnicode_FromFormat("<bpy_struct, %.200s at %p%s>",
1106 RNA_struct_identifier(self->ptr->type),
1107 self->ptr->data,
1108 extra_info);
1109}
1110
1111static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
1112{
1113 ID *id = self->ptr->owner_id;
1114 PyObject *tmp_str;
1115 PyObject *ret;
1116
1117 if (id == nullptr || !PYRNA_STRUCT_IS_VALID(self) || (DEG_get_original(id) != id)) {
1118 /* fallback */
1119 return pyrna_struct_str(self);
1120 }
1121
1122 tmp_str = PyUnicode_FromString(id->name + 2);
1123
1124 if (RNA_struct_is_ID(self->ptr->type) && (id->flag & ID_FLAG_EMBEDDED_DATA) == 0) {
1125 ret = PyUnicode_FromFormat(
1126 "bpy.data.%s[%R]", BKE_idtype_idcode_to_name_plural(id->id_type()), tmp_str);
1127 }
1128 else {
1129 ID *real_id = nullptr;
1130 const std::optional<std::string> path = RNA_path_from_real_ID_to_struct(
1131 G_MAIN, &self->ptr.value(), &real_id);
1132 if (path) {
1133 /* 'real_id' may be nullptr in some cases, although the only valid one is evaluated data,
1134 * which should have already been caught above.
1135 * So assert, but handle it without crashing for release builds. */
1136 BLI_assert(real_id != nullptr);
1137
1138 if (real_id != nullptr) {
1139 Py_DECREF(tmp_str);
1140 tmp_str = PyUnicode_FromString(real_id->name + 2);
1141 ret = PyUnicode_FromFormat("bpy.data.%s[%R].%s",
1142 BKE_idtype_idcode_to_name_plural(real_id->id_type()),
1143 tmp_str,
1144 path->c_str());
1145 }
1146 else {
1147 /* Can't find the path, print something useful as a fallback. */
1148 ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
1150 tmp_str,
1151 RNA_struct_identifier(self->ptr->type));
1152 }
1153 }
1154 else {
1155 /* Can't find the path, print something useful as a fallback. */
1156 ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
1158 tmp_str,
1159 RNA_struct_identifier(self->ptr->type));
1160 }
1161 }
1162
1163 Py_DECREF(tmp_str);
1164
1165 return ret;
1166}
1167
1168static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
1169{
1170 PyObject *ret;
1171 PointerRNA ptr;
1172 const char *name;
1173 const char *type_id = nullptr;
1174 char type_lower[64];
1175 char type_count[16];
1176 int type;
1177
1179
1180 type = RNA_property_type(self->prop);
1181
1182 if (RNA_enum_id_from_value(rna_enum_property_type_items, type, &type_id) == 0) {
1183 /* Should never happen. */
1184 PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error");
1185 return nullptr;
1186 }
1187
1188 STRNCPY_UTF8(type_lower, type_id);
1189 BLI_str_tolower_ascii(type_lower, sizeof(type_lower));
1190
1191 int len = -1;
1192 if (type == PROP_COLLECTION) {
1194 }
1195 else if (RNA_property_array_check(self->prop)) {
1196 len = pyrna_prop_array_length(reinterpret_cast<BPy_PropertyArrayRNA *>(self));
1197 }
1198
1199 if (len != -1) {
1200 SNPRINTF_UTF8(type_count, "[%d]", len);
1201 }
1202 else {
1203 type_count[0] = '\0';
1204 }
1205
1206 /* If a pointer, try to print name of pointer target too. */
1207 if (type == PROP_POINTER) {
1208 ptr = RNA_property_pointer_get(&self->ptr.value(), self->prop);
1209 name = RNA_struct_name_get_alloc(&ptr, nullptr, 0, nullptr);
1210
1211 if (name) {
1212 ret = PyUnicode_FromFormat("<bpy_%.200s%.200s, %.200s.%.200s(\"%.200s\")>",
1213 type_lower,
1214 type_count,
1215 RNA_struct_identifier(self->ptr->type),
1217 name);
1218 MEM_delete(name);
1219 return ret;
1220 }
1221 }
1222 if (type == PROP_COLLECTION) {
1223 if (std::optional<PointerRNA> c_ptr = RNA_property_collection_type_get(&self->ptr.value(),
1224 self->prop))
1225 {
1226 return PyUnicode_FromFormat("<bpy_%.200s%.200s, %.200s>",
1227 type_lower,
1228 type_count,
1229 RNA_struct_identifier(c_ptr->type));
1230 }
1231 }
1232
1233 return PyUnicode_FromFormat("<bpy_%.200s%.200s, %.200s.%.200s>",
1234 type_lower,
1235 type_count,
1236 RNA_struct_identifier(self->ptr->type),
1238}
1239
1240static PyObject *pyrna_prop_repr_ex(BPy_PropertyRNA *self, const int index_dim, const int index)
1241{
1242 ID *id = self->ptr->owner_id;
1243 PyObject *tmp_str;
1244 PyObject *ret;
1245
1247
1248 if (id == nullptr) {
1249 /* Fallback. */
1250 return pyrna_prop_str(self);
1251 }
1252
1253 tmp_str = PyUnicode_FromString(id->name + 2);
1254
1255 /* Note that using G_MAIN is absolutely not ideal, but we have no access to actual Main DB from
1256 * here. */
1257 ID *real_id = nullptr;
1258 const std::optional<std::string> path = RNA_path_from_real_ID_to_property_index(
1259 G_MAIN, &self->ptr.value(), self->prop, index_dim, index, &real_id);
1260
1261 if (path) {
1262 if (real_id != id) {
1263 Py_DECREF(tmp_str);
1264 tmp_str = PyUnicode_FromString(real_id->name + 2);
1265 }
1266 const char *data_delim = ((*path)[0] == '[') ? "" : ".";
1267 ret = PyUnicode_FromFormat("bpy.data.%s[%R]%s%s",
1268 BKE_idtype_idcode_to_name_plural(real_id->id_type()),
1269 tmp_str,
1270 data_delim,
1271 path->c_str());
1272 }
1273 else {
1274 /* Can't find the path, print something useful as a fallback. */
1275 ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
1277 tmp_str,
1279 }
1280
1281 Py_DECREF(tmp_str);
1282
1283 return ret;
1284}
1285
1286static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
1287{
1288 return pyrna_prop_repr_ex(self, 0, -1);
1289}
1290
1292{
1293 return pyrna_prop_repr_ex(
1294 reinterpret_cast<BPy_PropertyRNA *>(self), self->arraydim, self->arrayoffset);
1295}
1296
1297static PyObject *pyrna_func_repr(BPy_FunctionRNA *self)
1298{
1299 return PyUnicode_FromFormat("<%.200s %.200s.%.200s()>",
1300 Py_TYPE(self)->tp_name,
1301 RNA_struct_identifier(self->ptr->type),
1303}
1304
1305static Py_hash_t pyrna_struct_hash(BPy_StructRNA *self)
1306{
1307 return Py_HashPointer(self->ptr->data);
1308}
1309
1310/* From Python's meth_hash v3.1.2. */
1312{
1313 long x, y;
1314 if (!*self->ptr) {
1315 x = 0;
1316 }
1317 else {
1318 x = Py_HashPointer(self->ptr->data);
1319 if (x == -1) {
1320 return -1;
1321 }
1322 }
1323 y = Py_HashPointer(static_cast<void *>(self->prop));
1324 if (y == -1) {
1325 return -1;
1326 }
1327 x ^= y;
1328 if (x == -1) {
1329 x = -2;
1330 }
1331 return x;
1332}
1333
1334#ifdef USE_PYRNA_STRUCT_REFERENCE
1335static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
1336{
1337 Py_VISIT(self->reference);
1338 return 0;
1339}
1340
1341static int pyrna_struct_clear(BPy_StructRNA *self)
1342{
1343 Py_CLEAR(self->reference);
1344 return 0;
1345}
1346#endif /* !USE_PYRNA_STRUCT_REFERENCE */
1347
1348#ifdef USE_PYRNA_STRUCT_REFERENCE
1349static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
1350{
1351 if (self->reference) {
1352 PyObject_GC_UnTrack(self);
1353 Py_CLEAR(self->reference);
1354 }
1355 /* Reference is now nullptr. */
1356
1357 if (reference) {
1358 self->reference = reference;
1359 Py_INCREF(reference);
1360 BLI_assert(!PyObject_GC_IsTracked((PyObject *)self));
1361 PyObject_GC_Track(self);
1362 }
1363}
1364#endif /* !USE_PYRNA_STRUCT_REFERENCE */
1365
1366static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
1367{
1368 const EnumPropertyItem *item;
1369 const char *result;
1370 bool free = false;
1371
1372 RNA_property_enum_items(BPY_context_get(), ptr, prop, &item, nullptr, &free);
1373 if (item) {
1374 result = pyrna_enum_repr(item);
1375 }
1376 else {
1377 result = "";
1378 }
1379
1380 if (free) {
1381 MEM_delete(item);
1382 }
1383
1384 return result;
1385}
1386
1388 PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *r_value, const char *error_prefix)
1389{
1390 const char *param = PyUnicode_AsUTF8(item);
1391
1392 if (param == nullptr) {
1393 PyErr_Format(PyExc_TypeError,
1394 "%.200s expected a string enum, not %.200s",
1395 error_prefix,
1396 Py_TYPE(item)->tp_name);
1397 return -1;
1398 }
1399
1400 if (!RNA_property_enum_value(BPY_context_get(), ptr, prop, param, r_value)) {
1401 const char *enum_str = pyrna_enum_as_string(ptr, prop);
1402 PyErr_Format(PyExc_TypeError,
1403 "%.200s enum \"%.200s\" not found in (%s)",
1404 error_prefix,
1405 param,
1406 enum_str);
1407 MEM_delete(enum_str);
1408 return -1;
1409 }
1410
1411 return 0;
1412}
1413
1415 PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
1416{
1417 const EnumPropertyItem *item;
1418 int ret;
1419 bool free = false;
1420
1421 *r_value = 0;
1422
1423 if (!PyAnySet_Check(value)) {
1424 PyErr_Format(PyExc_TypeError,
1425 "%.200s, %.200s.%.200s expected a set, not a %.200s",
1426 error_prefix,
1429 Py_TYPE(value)->tp_name);
1430 return -1;
1431 }
1432
1433 RNA_property_enum_items(BPY_context_get(), ptr, prop, &item, nullptr, &free);
1434
1435 if (item) {
1436 ret = pyrna_enum_bitfield_from_set(item, value, r_value, error_prefix);
1437 }
1438 else {
1439 if (PySet_GET_SIZE(value)) {
1440 PyErr_Format(PyExc_TypeError,
1441 "%.200s: empty enum \"%.200s\" could not have any values assigned",
1442 error_prefix,
1444 ret = -1;
1445 }
1446 else {
1447 ret = 0;
1448 }
1449 }
1450
1451 if (free) {
1452 MEM_delete(item);
1453 }
1454
1455 return ret;
1456}
1457
1458static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
1459{
1460 PyObject *item, *ret = nullptr;
1461
1462 if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1463 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1464
1465 ret = PySet_New(nullptr);
1466
1467 if (RNA_property_enum_bitflag_identifiers(BPY_context_get(), ptr, prop, val, identifier)) {
1468 int index;
1469
1470 for (index = 0; identifier[index]; index++) {
1471 item = PyUnicode_FromString(identifier[index]);
1472 PySet_Add(ret, item);
1473 Py_DECREF(item);
1474 }
1475 }
1476 }
1477 else {
1478 const char *identifier;
1479 if (RNA_property_enum_identifier(BPY_context_get(), ptr, prop, val, &identifier)) {
1480 ret = PyUnicode_FromString(identifier);
1481 }
1482 else {
1483 /* Static, no need to free. */
1484 const EnumPropertyItem *enum_item;
1485 bool free_dummy;
1486 RNA_property_enum_items_ex(nullptr, ptr, prop, true, &enum_item, nullptr, &free_dummy);
1487 BLI_assert(!free_dummy);
1488
1489 /* Do not print warning in case of #rna_enum_dummy_NULL_items,
1490 * this one will never match any value... */
1491 if (enum_item != rna_enum_dummy_NULL_items) {
1492 const char *ptr_name = RNA_struct_name_get_alloc(ptr, nullptr, 0, nullptr);
1493
1494 /* Prefer not to fail silently in case of API errors, maybe disable it later. */
1496 "current value '%d' "
1497 "matches no enum in '%s', '%s', '%s'",
1498 val,
1500 ptr_name,
1502
1503#if 0 /* Gives Python decoding errors while generating docs :( */
1504 char error_str[256];
1505 BLI_snprintf_utf8(error_str,
1506 sizeof(error_str),
1507 "RNA Warning: Current value \"%d\" "
1508 "matches no enum in '%s', '%s', '%s'",
1509 val,
1511 ptr_name,
1513
1514 PyErr_Warn(PyExc_RuntimeWarning, error_str);
1515#endif
1516
1517 if (ptr_name) {
1518 MEM_delete(ptr_name);
1519 }
1520 }
1521
1522 ret = PyUnicode_FromString("");
1523#if 0
1524 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1525 ret = nullptr;
1526#endif
1527 }
1528 }
1529
1530 return ret;
1531}
1532
1534{
1535 PyObject *ret;
1536 const int type = RNA_property_type(prop);
1537
1538 if (const DeprecatedRNA *deprecated = RNA_property_deprecated(prop)) {
1539 pyrna_prop_warn_deprecated(ptr, prop, deprecated);
1540 }
1541
1542 if (RNA_property_array_check(prop)) {
1543 return pyrna_py_from_array(ptr, prop);
1544 }
1545
1546 /* See if we can coerce into a Python type - 'PropertyType'. */
1547 switch (type) {
1548 case PROP_BOOLEAN:
1549 ret = PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
1550 break;
1551 case PROP_INT:
1552 ret = PyLong_FromLong(RNA_property_int_get(ptr, prop));
1553 break;
1554 case PROP_FLOAT:
1555 ret = PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
1556 break;
1557 case PROP_STRING: {
1558 const int subtype = RNA_property_subtype(prop);
1559 const char *buf;
1560 int buf_len;
1561 char buf_fixed[32];
1562
1563 buf = RNA_property_string_get_alloc(ptr, prop, buf_fixed, sizeof(buf_fixed), &buf_len);
1564#ifdef USE_STRING_COERCE
1565 /* Only file paths get special treatment, they may contain non UTF8 chars. */
1566 if (subtype == PROP_BYTESTRING) {
1567 ret = PyBytes_FromStringAndSize(buf, buf_len);
1568 }
1569 else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1570 ret = PyC_UnicodeFromBytesAndSize(buf, buf_len);
1571 }
1572 else {
1573 ret = PyUnicode_FromStringAndSize(buf, buf_len);
1574 }
1575#else /* USE_STRING_COERCE */
1576 if (subtype == PROP_BYTESTRING) {
1577 ret = PyBytes_FromStringAndSize(buf, buf_len);
1578 }
1579 else {
1580 ret = PyUnicode_FromStringAndSize(buf, buf_len);
1581 }
1582#endif /* USE_STRING_COERCE */
1583 if (buf_fixed != buf) {
1584 MEM_delete(buf);
1585 }
1586 break;
1587 }
1588 case PROP_ENUM: {
1589 ret = pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
1590 break;
1591 }
1592 case PROP_POINTER: {
1593 PointerRNA newptr;
1594 newptr = RNA_property_pointer_get(ptr, prop);
1595 if (newptr) {
1597 }
1598 else {
1599 ret = Py_None;
1600 Py_INCREF(ret);
1601 }
1602 break;
1603 }
1604 case PROP_COLLECTION:
1605 ret = pyrna_prop_CreatePyObject(ptr, prop);
1606 break;
1607 default:
1608 PyErr_Format(PyExc_TypeError,
1609 "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)",
1610 type);
1611 ret = nullptr;
1612 break;
1613 }
1614
1615 return ret;
1616}
1617
1619 PyObject *kw,
1620 const bool all_args,
1621 const char *error_prefix)
1622{
1623 int error_val = 0;
1624 int totkw;
1625 const char *arg_name = nullptr;
1626 PyObject *item;
1627
1628 totkw = kw ? PyDict_Size(kw) : 0;
1629
1630 RNA_STRUCT_BEGIN (ptr, prop) {
1631 arg_name = RNA_property_identifier(prop);
1632
1633 if (STREQ(arg_name, "rna_type")) {
1634 continue;
1635 }
1636
1637 if (kw == nullptr) {
1638 PyErr_Format(
1639 PyExc_TypeError, "%.200s: no keywords, expected \"%.200s\"", error_prefix, arg_name);
1640 error_val = -1;
1641 break;
1642 }
1643
1644 item = PyDict_GetItemString(kw, arg_name); /* Won't set an error. */
1645
1646 if (item == nullptr) {
1647 if (all_args) {
1648 PyErr_Format(PyExc_TypeError,
1649 "%.200s: keyword \"%.200s\" missing",
1650 error_prefix,
1651 arg_name ? arg_name : "<UNKNOWN>");
1652 error_val = -1; /* pyrna_py_to_prop sets the error. */
1653 break;
1654 }
1655 }
1656 else {
1657 if (pyrna_py_to_prop(ptr, prop, nullptr, item, error_prefix, nullptr)) {
1658 error_val = -1;
1659 break;
1660 }
1661 totkw--;
1662 }
1663 }
1665
1666 if (error_val == 0 && totkw > 0) { /* Some keywords were given that were not used :/. */
1667 PyObject *key, *value;
1668 Py_ssize_t pos = 0;
1669
1670 while (PyDict_Next(kw, &pos, &key, &value)) {
1671 arg_name = PyUnicode_AsUTF8(key);
1672 if (RNA_struct_find_property(ptr, arg_name) == nullptr) {
1673 break;
1674 }
1675 arg_name = nullptr;
1676 }
1677
1678 PyErr_Format(PyExc_TypeError,
1679 "%.200s: keyword \"%.200s\" unrecognized",
1680 error_prefix,
1681 arg_name ? arg_name : "<UNKNOWN>");
1682 error_val = -1;
1683 }
1684
1685 return error_val;
1686}
1687
1689 PropertyRNA *prop,
1690 void *data,
1691 PyObject *value,
1692 const char *error_prefix,
1693 PyObject **r_value_coerce)
1694{
1695 /* XXX hard limits should be checked here. */
1696 const int type = RNA_property_type(prop);
1697
1698 if (const DeprecatedRNA *deprecated = RNA_property_deprecated(prop)) {
1699 pyrna_prop_warn_deprecated(ptr, prop, deprecated);
1700 }
1701
1702 if (RNA_property_array_check(prop)) {
1703 /* Done getting the length. */
1704 if (pyrna_py_to_array(ptr, prop, static_cast<char *>(data), value, error_prefix) == -1) {
1705 return -1;
1706 }
1707 }
1708 else {
1709 /* Normal Property (not an array). */
1710
1711 /* See if we can coerce into a Python type - 'PropertyType'. */
1712 switch (type) {
1713 case PROP_BOOLEAN: {
1714 int param;
1715 /* Prefer not to have an exception here
1716 * however so many poll functions return None or a valid Object.
1717 * It's a hassle to convert these into a bool before returning. */
1718 if (RNA_parameter_flag(prop) & PARM_OUTPUT) {
1719 param = PyObject_IsTrue(value);
1720 }
1721 else {
1722 param = PyC_Long_AsI32(value);
1723
1724 if (param & ~1) [[unlikely]] { /* Only accept 0/1. */
1725 param = -1; /* Error out below. */
1726 }
1727 }
1728
1729 if (param == -1) {
1730 PyErr_Format(PyExc_TypeError,
1731 "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
1732 error_prefix,
1735 Py_TYPE(value)->tp_name);
1736 return -1;
1737 }
1738
1739 if (data) {
1740 *(static_cast<bool *>(data)) = param;
1741 }
1742 else {
1743 RNA_property_boolean_set(ptr, prop, param);
1744 }
1745
1746 break;
1747 }
1748 case PROP_INT: {
1749 int overflow;
1750 const long param = PyLong_AsLongAndOverflow(value, &overflow);
1751 if (overflow || (param > INT_MAX) || (param < INT_MIN)) {
1752 PyErr_Format(PyExc_ValueError,
1753 "%.200s %.200s.%.200s value not in 'int' range "
1754 "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
1755 error_prefix,
1758 return -1;
1759 }
1760 if (param == -1 && PyErr_Occurred()) {
1761 PyErr_Format(PyExc_TypeError,
1762 "%.200s %.200s.%.200s expected an int type, not %.200s",
1763 error_prefix,
1766 Py_TYPE(value)->tp_name);
1767 return -1;
1768 }
1769
1770 int param_i = int(param);
1771 if (data) {
1772 RNA_property_int_clamp(ptr, prop, &param_i);
1773 *(static_cast<int *>(data)) = param_i;
1774 }
1775 else {
1776 RNA_property_int_set(ptr, prop, param_i);
1777 }
1778
1779 break;
1780 }
1781 case PROP_FLOAT: {
1782 const float param = PyFloat_AsDouble(value);
1783 if (PyErr_Occurred()) {
1784 PyErr_Format(PyExc_TypeError,
1785 "%.200s %.200s.%.200s expected a float type, not %.200s",
1786 error_prefix,
1789 Py_TYPE(value)->tp_name);
1790 return -1;
1791 }
1792
1793 if (data) {
1794 RNA_property_float_clamp(ptr, prop, const_cast<float *>(&param));
1795 *(static_cast<float *>(data)) = param;
1796 }
1797 else {
1798 RNA_property_float_set(ptr, prop, param);
1799 }
1800
1801 break;
1802 }
1803 case PROP_STRING: {
1804 const int flag = RNA_property_flag(prop);
1805 const int subtype = RNA_property_subtype(prop);
1806 const char *param;
1807
1808 if (value == Py_None) {
1809 if ((flag & PROP_NEVER_NULL) == 0) {
1810 if (data) {
1811 if (flag & PROP_THICK_WRAP) {
1812 *static_cast<char *>(data) = 0;
1813 }
1814 else {
1815 *(static_cast<char **>(data)) = static_cast<char *>(nullptr);
1816 }
1817 }
1818 else {
1819 RNA_property_string_set(ptr, prop, nullptr);
1820 }
1821 }
1822 else {
1823 PyErr_Format(PyExc_TypeError,
1824 "%.200s %.200s.%.200s doesn't support None from string types",
1825 error_prefix,
1828 return -1;
1829 }
1830 }
1831 else if (subtype == PROP_BYTESTRING) {
1832
1833 /* Byte String. */
1834
1835 param = PyBytes_AsString(value);
1836
1837 if (param == nullptr) {
1838 if (PyBytes_Check(value)) {
1839 /* there was an error assigning a string type,
1840 * rather than setting a new error, prefix the existing one
1841 */
1842 PyC_Err_Format_Prefix(PyExc_TypeError,
1843 "%.200s %.200s.%.200s error assigning bytes",
1844 error_prefix,
1847 }
1848 else {
1849 PyErr_Format(PyExc_TypeError,
1850 "%.200s %.200s.%.200s expected a bytes type, not %.200s",
1851 error_prefix,
1854 Py_TYPE(value)->tp_name);
1855 }
1856
1857 return -1;
1858 }
1859
1860 if (data) {
1861 if (flag & PROP_THICK_WRAP) {
1862 BLI_strncpy(static_cast<char *>(data), param, RNA_property_string_maxlength(prop));
1863 }
1864 else {
1865 *(static_cast<char **>(data)) = const_cast<char *>(param);
1866 }
1867 }
1868 else {
1869 RNA_property_string_set_bytes(ptr, prop, param, PyBytes_Size(value));
1870 }
1871 }
1872 else {
1873/* Unicode String. */
1874#ifdef USE_STRING_COERCE
1875 PyObject *value_coerce = nullptr;
1876 if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1877 /* TODO: get size. */
1878 param = PyC_UnicodeAsBytes(value, &value_coerce);
1879 }
1880 else {
1881 param = PyUnicode_AsUTF8(value);
1882 }
1883#else /* USE_STRING_COERCE */
1884 param = PyUnicode_AsUTF8(value);
1885#endif /* USE_STRING_COERCE */
1886
1887 if (param == nullptr) {
1888 if (PyUnicode_Check(value)) {
1889 /* there was an error assigning a string type,
1890 * rather than setting a new error, prefix the existing one
1891 */
1892 PyC_Err_Format_Prefix(PyExc_TypeError,
1893 "%.200s %.200s.%.200s error assigning string",
1894 error_prefix,
1897 }
1898 else {
1899 PyErr_Format(PyExc_TypeError,
1900 "%.200s %.200s.%.200s expected a string type, not %.200s",
1901 error_prefix,
1904 Py_TYPE(value)->tp_name);
1905 }
1906
1907 return -1;
1908 }
1909
1910 if ((flag & PROP_PATH_SUPPORTS_BLEND_RELATIVE) == 0) {
1911 if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH)) {
1912 if (BLI_path_is_rel(param)) {
1913 char warning_buf[256];
1914 SNPRINTF_UTF8(warning_buf,
1915 "%.200s.%.200s: does not support blend relative \"//\" prefix",
1918 PyErr_WarnEx(PyExc_RuntimeWarning, warning_buf, 1);
1919 }
1920 }
1921 }
1922
1923 /* Same as bytes (except for UTF8 string copy). */
1924 /* NOTE: a function parameter without #PROP_THICK_WRAP only stores a pointer to
1925 * `param`, which must then outlive the call, see #pyrna_func_vectorcall. */
1926 bool param_is_ref = false;
1927 if (data) {
1928 if (flag & PROP_THICK_WRAP) {
1930 static_cast<char *>(data), param, RNA_property_string_maxlength(prop));
1931 }
1932 else {
1933 *(static_cast<char **>(data)) = const_cast<char *>(param);
1934 param_is_ref = true;
1935 }
1936 }
1937 else {
1938 RNA_property_string_set(ptr, prop, param);
1939 }
1940
1941#ifdef USE_STRING_COERCE
1942 if (value_coerce) [[unlikely]] {
1943 if (param_is_ref && r_value_coerce) [[unlikely]] {
1944 /* `value` doesn't own `param`, hand the only reference to the caller. */
1945 *r_value_coerce = value_coerce;
1946 }
1947 else {
1948 /* A reference without `r_value_coerce` is only reachable for string return
1949 * values, which must be thick wrapped. */
1950 BLI_assert(!param_is_ref);
1951 Py_DECREF(value_coerce);
1952 }
1953 }
1954#else /* USE_STRING_COERCE */
1955 UNUSED_VARS(param_is_ref);
1956#endif /* USE_STRING_COERCE */
1957 }
1958 break;
1959 }
1960 case PROP_ENUM: {
1961 int val = 0;
1962
1963 /* Type checking is done by each function. */
1964 if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1965 /* Set of enum items, concatenate all values with OR. */
1966 if (pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) == -1) {
1967 return -1;
1968 }
1969 }
1970 else {
1971 /* Simple enum string. */
1972 if (pyrna_string_to_enum(value, ptr, prop, &val, error_prefix) == -1) {
1973 return -1;
1974 }
1975 }
1976
1977 if (data) {
1978 *(static_cast<int *>(data)) = val;
1979 }
1980 else {
1981 RNA_property_enum_set(ptr, prop, val);
1982 }
1983
1984 break;
1985 }
1986 case PROP_POINTER: {
1987 PyObject *value_new = nullptr;
1988
1990 const int flag = RNA_property_flag(prop);
1991 const int flag_parameter = RNA_parameter_flag(prop);
1992
1993 /* This is really nasty! Done so we can fake the operator having direct properties, eg:
1994 * layout.prop(self, "filepath")
1995 * ... which in fact should be:
1996 * layout.prop(self.properties, "filepath")
1997 *
1998 * we need to do this trick.
1999 * if the prop is not an operator type and the PyObject is an operator,
2000 * use its properties in place of itself.
2001 *
2002 * This is so bad that it is almost a good reason to do away with fake
2003 * 'self.properties -> self'
2004 * class mixing. If this causes problems in the future it should be removed.
2005 */
2006 if ((ptr_type == RNA_AnyType) && BPy_StructRNA_Check(value)) {
2007 const StructRNA *base_type = RNA_struct_base_child_of(
2008 (reinterpret_cast<const BPy_StructRNA *>(value))->ptr->type, nullptr);
2009 if (ELEM(base_type, RNA_Operator, RNA_Gizmo)) {
2010 value = PyObject_GetAttr(value, bpy_intern_str_properties);
2011 value_new = value;
2012 }
2013 }
2014
2015 /* if property is an OperatorProperties/GizmoProperties/PropertyGroup pointer and value
2016 * is a map, forward back to pyrna_pydict_to_props */
2017 if (PyDict_Check(value)) {
2018 const StructRNA *base_type = RNA_struct_base_child_of(ptr_type, nullptr);
2019 if (ELEM(base_type, RNA_OperatorProperties, RNA_GizmoProperties, RNA_PropertyGroup)) {
2020 PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
2021 if (opptr.has_type()) {
2022 return pyrna_pydict_to_props(&opptr, value, false, error_prefix);
2023 }
2024 /* Converting a dictionary to properties is not supported
2025 * for function arguments, this would be nice to support but is complicated
2026 * because the operator type needs to be read from another function argument
2027 * and allocated data needs to be freed. See #135245. */
2028
2029 /* This is only expected to happen for RNA functions. */
2030 BLI_assert(ptr->type == RNA_Function);
2031 if (ptr->type != RNA_Function) {
2032 PyErr_Format(PyExc_TypeError,
2033 "%.200s %.200s.%.200s internal error coercing a dict for %.200s type",
2034 error_prefix,
2038 return -1;
2039 }
2040 }
2041 }
2042
2043 /* Another exception, allow passing a collection as an RNA property. */
2044 if (Py_TYPE(value) == &pyrna_prop_collection_Type) { /* Ok to ignore idprop collections. */
2045 BPy_PropertyRNA *value_prop = reinterpret_cast<BPy_PropertyRNA *>(value);
2046 if (std::optional<PointerRNA> c_ptr = RNA_property_collection_type_get(
2047 &value_prop->ptr.value(), value_prop->prop))
2048 {
2049 value = pyrna_struct_CreatePyObject(&c_ptr.value());
2050 value_new = value;
2051 }
2052 else {
2053 PyErr_Format(PyExc_TypeError,
2054 "%.200s %.200s.%.200s collection has no type, "
2055 "cannot be used as a %.200s type",
2056 error_prefix,
2060 return -1;
2061 }
2062 }
2063
2064 BPy_StructRNA *param;
2065 if (value == Py_None) {
2066 if (flag & PROP_NEVER_NULL) {
2067 PyErr_Format(PyExc_TypeError,
2068 "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
2069 error_prefix,
2073 Py_XDECREF(value_new);
2074 return -1;
2075 }
2076 param = nullptr;
2077 }
2078 else {
2079 if (!BPy_StructRNA_Check(value)) {
2080 PyErr_Format(PyExc_TypeError,
2081 "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
2082 error_prefix,
2086 Py_TYPE(value)->tp_name);
2087 Py_XDECREF(value_new);
2088 return -1;
2089 }
2090 param = reinterpret_cast<BPy_StructRNA *>(value);
2091
2092 const ID *value_owner_id = (reinterpret_cast<BPy_StructRNA *>(value))->ptr->owner_id;
2093 if (value_owner_id != nullptr) {
2094 if ((flag & PROP_ID_SELF_CHECK) && (ptr->owner_id == value_owner_id)) {
2095 PyErr_Format(PyExc_TypeError,
2096 "%.200s %.200s.%.200s ID type does not support assignment to itself",
2097 error_prefix,
2100 Py_XDECREF(value_new);
2101 return -1;
2102 }
2103
2104 if (value_owner_id->tag & ID_TAG_TEMP_MAIN) {
2105 /* Allow passing temporary ID's to functions, but not attribute assignment. */
2106 if (ptr->type != RNA_Function) {
2107 PyErr_Format(PyExc_TypeError,
2108 "%.200s %.200s.%.200s ID type assignment is temporary, cannot assign",
2109 error_prefix,
2112 Py_XDECREF(value_new);
2113 return -1;
2114 }
2115 }
2116 }
2117 }
2118
2119 bool raise_error = false;
2120 if (data) {
2121
2122 if (flag_parameter & PARM_RNAPTR) {
2123 if (flag & PROP_THICK_WRAP) {
2124 if (param == nullptr) {
2125 *reinterpret_cast<PointerRNA *>(data) = {};
2126 }
2127 else if (RNA_struct_is_a(param->ptr->type, ptr_type)) {
2128 *reinterpret_cast<PointerRNA *>(data) = *param->ptr;
2129 }
2130 else {
2131 raise_error = true;
2132 }
2133 }
2134 else {
2135 /* For function calls, we sometimes want to pass the 'ptr' directly,
2136 * but watch out that it remains valid!
2137 * We could possibly support this later if needed. */
2138 BLI_assert(value_new == nullptr);
2139 if (param == nullptr) {
2140 *(static_cast<void **>(data)) = nullptr;
2141 }
2142 else if (RNA_struct_is_a(param->ptr->type, ptr_type)) {
2143 *(static_cast<PointerRNA **>(data)) = &param->ptr.value();
2144 }
2145 else {
2146 raise_error = true;
2147 }
2148 }
2149 }
2150 else if (param == nullptr) {
2151 *(static_cast<void **>(data)) = nullptr;
2152 }
2153 else if (RNA_struct_is_a(param->ptr->type, ptr_type)) {
2154 *(static_cast<void **>(data)) = param->ptr->data;
2155 }
2156 else {
2157 raise_error = true;
2158 }
2159 }
2160 else {
2161 /* Data == nullptr, assign to RNA. */
2162 if ((param == nullptr) || RNA_struct_is_a(param->ptr->type, ptr_type)) {
2163 ReportList reports;
2166 ptr, prop, (param == nullptr) ? PointerRNA() : *param->ptr, &reports);
2167 const int err = BPy_reports_to_error(&reports, PyExc_RuntimeError, true);
2168 if (err == -1) {
2169 Py_XDECREF(value_new);
2170 return -1;
2171 }
2172 }
2173 else {
2174 raise_error = true;
2175 }
2176 }
2177
2178 if (raise_error) {
2179 if (pyrna_struct_validity_check(param) == -1) {
2180 /* Error set. */
2181 }
2182 else {
2183 PointerRNA tmp = RNA_pointer_create_discrete(nullptr, ptr_type, nullptr);
2184 PyErr_Format(PyExc_TypeError,
2185 "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
2186 error_prefix,
2190 RNA_struct_identifier(param->ptr->type));
2191 }
2192 Py_XDECREF(value_new);
2193 return -1;
2194 }
2195
2196 Py_XDECREF(value_new);
2197
2198 break;
2199 }
2200 case PROP_COLLECTION: {
2201 Py_ssize_t seq_len, i;
2202 PyObject *item;
2203 PointerRNA itemptr;
2204 CollectionVector *lb;
2205
2206 lb = (data) ? static_cast<CollectionVector *>(data) : nullptr;
2207
2208 /* Convert a sequence of dict's into a collection. */
2209 if (!PySequence_Check(value)) {
2210 PyErr_Format(
2211 PyExc_TypeError,
2212 "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
2213 error_prefix,
2216 Py_TYPE(value)->tp_name);
2217 return -1;
2218 }
2219
2220 seq_len = PySequence_Size(value);
2221 for (i = 0; i < seq_len; i++) {
2222 item = PySequence_GetItem(value, i);
2223
2224 if (item == nullptr) {
2225 PyErr_Format(
2226 PyExc_TypeError,
2227 "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
2228 error_prefix,
2231 i);
2232 Py_XDECREF(item);
2233 return -1;
2234 }
2235
2236 if (PyDict_Check(item) == 0) {
2237 PyErr_Format(PyExc_TypeError,
2238 "%.200s %.200s.%.200s expected a each sequence "
2239 "member to be a dict for an RNA collection, not %.200s",
2240 error_prefix,
2243 Py_TYPE(item)->tp_name);
2244 Py_XDECREF(item);
2245 return -1;
2246 }
2247
2248 if (lb) {
2249 lb->items.append(itemptr);
2250 }
2251 else {
2252 RNA_property_collection_add(ptr, prop, &itemptr);
2253 }
2254
2256 &itemptr, item, true, "Converting a Python list to an RNA collection") == -1)
2257 {
2258 PyObject *msg = PyC_ExceptionBuffer();
2259 const char *msg_char = PyUnicode_AsUTF8(msg);
2260 PyErr_Clear();
2261
2262 PyErr_Format(PyExc_TypeError,
2263 "%.200s %.200s.%.200s error converting a member of a collection "
2264 "from a dicts into an RNA collection, failed with: %s",
2265 error_prefix,
2268 msg_char);
2269
2270 Py_DECREF(item);
2271 Py_DECREF(msg);
2272 return -1;
2273 }
2274 Py_DECREF(item);
2275 }
2276
2277 break;
2278 }
2279 default:
2280 PyErr_Format(PyExc_AttributeError,
2281 "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
2282 error_prefix,
2285 return -1;
2286 }
2287 }
2288
2289 /* Run RNA property functions. */
2290 if (RNA_property_update_check(prop)) {
2292 }
2293
2294 return 0;
2295}
2296
2298{
2300 return pyrna_py_from_array_index(self, &self->ptr.value(), self->prop, index);
2301}
2302
2303static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
2304{
2305 int ret = 0;
2306 PointerRNA *ptr = &self->ptr.value();
2307 PropertyRNA *prop = self->prop;
2308
2309 const int totdim = RNA_property_array_dimension(ptr, prop, nullptr);
2310
2311 if (totdim > 1) {
2312 // char error_str[512];
2314 &self->ptr.value(), self->prop, self->arraydim, self->arrayoffset, index, value, "") ==
2315 -1)
2316 {
2317 /* Error is set. */
2318 ret = -1;
2319 }
2320 }
2321 else {
2322 /* See if we can coerce into a Python type - 'PropertyType'. */
2323 switch (RNA_property_type(prop)) {
2324 case PROP_BOOLEAN: {
2325 const int param = PyC_Long_AsBool(value);
2326
2327 if (param == -1) {
2328 /* Error is set. */
2329 ret = -1;
2330 }
2331 else {
2332 RNA_property_boolean_set_index(ptr, prop, index, param);
2333 }
2334 break;
2335 }
2336 case PROP_INT: {
2337 int param = PyC_Long_AsI32(value);
2338 if (param == -1 && PyErr_Occurred()) {
2339 PyErr_SetString(PyExc_TypeError, "expected an int type");
2340 ret = -1;
2341 }
2342 else {
2343 RNA_property_int_clamp(ptr, prop, &param);
2344 RNA_property_int_set_index(ptr, prop, index, param);
2345 }
2346 break;
2347 }
2348 case PROP_FLOAT: {
2349 float param = PyFloat_AsDouble(value);
2350 if (PyErr_Occurred()) {
2351 PyErr_SetString(PyExc_TypeError, "expected a float type");
2352 ret = -1;
2353 }
2354 else {
2355 RNA_property_float_clamp(ptr, prop, &param);
2356 RNA_property_float_set_index(ptr, prop, index, param);
2357 }
2358 break;
2359 }
2360 default:
2361 PyErr_SetString(PyExc_AttributeError, "not an array type");
2362 ret = -1;
2363 break;
2364 }
2365 }
2366
2367 /* Run RNA property functions. */
2368 if (RNA_property_update_check(prop)) {
2370 }
2371
2372 return ret;
2373}
2374
2375/* ---------------sequence------------------------------------------- */
2377{
2379
2380 if (RNA_property_array_dimension(&self->ptr.value(), self->prop, nullptr) > 1) {
2381 return RNA_property_multi_array_length(&self->ptr.value(), self->prop, self->arraydim);
2382 }
2383
2384 return RNA_property_array_length(&self->ptr.value(), self->prop);
2385}
2386
2388{
2390
2391 return RNA_property_collection_length(&self->ptr.value(), self->prop);
2392}
2393
2394/* bool functions are for speed, so we can avoid getting the length
2395 * of 1000's of items in a linked list for eg. */
2397{
2399
2400 return RNA_property_array_length(&self->ptr.value(), self->prop) ? 1 : 0;
2401}
2402
2404{
2406
2407 return !RNA_property_collection_is_empty(&self->ptr.value(), self->prop);
2408}
2409
2410/* notice getting the length of the collection is avoided unless negative
2411 * index is used or to detect internal error with a valid index.
2412 * This is done for faster lookups. */
2413#define PYRNA_PROP_COLLECTION_ABS_INDEX(ret_err) \
2414 if (keynum < 0) { \
2415 keynum_abs += RNA_property_collection_length(&self->ptr.value(), self->prop); \
2416 if (keynum_abs < 0) { \
2417 PyErr_Format(PyExc_IndexError, "bpy_prop_collection[%d]: out of range.", keynum); \
2418 return ret_err; \
2419 } \
2420 } \
2421 (void)0
2422
2427{
2428 if (value != Py_None) {
2430 const BPy_StructRNA *value_pyrna = reinterpret_cast<const BPy_StructRNA *>(value);
2431 if (!value_pyrna->ptr->has_type()) [[unlikely]] {
2432 /* It's important to use a `TypeError` as that is what's returned when `__getitem__` is
2433 * called on an object that doesn't support item access. */
2434 PyErr_Format(PyExc_TypeError,
2435 "'%.200s' object is not subscriptable (only iteration is supported)",
2436 Py_TYPE(value)->tp_name);
2437 return -1;
2438 }
2439 }
2440 return 0;
2441}
2442
2444 const char *error_prefix)
2445{
2446 PyErr_Format(PyExc_TypeError,
2447 "%.200s: %.200s.%.200s does not support string lookups",
2448 error_prefix,
2449 RNA_struct_identifier(self->ptr->type),
2451}
2452
2454 const char *error_prefix)
2455{
2458 return 0;
2459 }
2461 return -1;
2462}
2463
2464/* Internal use only. */
2465static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
2466{
2467 PointerRNA newptr;
2468 Py_ssize_t keynum_abs = keynum;
2469
2471
2473
2475 if (RNA_property_collection_lookup_int(&self->ptr.value(), self->prop, keynum_abs, &newptr)) {
2476 return pyrna_struct_CreatePyObject(&newptr);
2477 }
2478 }
2479 else {
2480 /* No callback defined, just iterate and find the nth item. */
2481 const int key = int(keynum_abs);
2482 PyObject *result = nullptr;
2483 bool found = false;
2485 RNA_property_collection_begin(&self->ptr.value(), self->prop, &iter);
2486 for (int i = 0; iter.valid; RNA_property_collection_next(&iter), i++) {
2487 if (i == key) {
2489 found = true;
2490 break;
2491 }
2492 }
2493 /* It's important to end the iterator after `result` has been created
2494 * so iterators may optionally invalidate items that were iterated over, see: #100286. */
2496 if (found) {
2498 Py_DECREF(result);
2499 result = nullptr; /* The exception has been set. */
2500 }
2501 return result;
2502 }
2503 }
2504
2505 const int len = RNA_property_collection_length(&self->ptr.value(), self->prop);
2506 if (keynum_abs >= len) {
2507 PyErr_Format(PyExc_IndexError,
2508 "bpy_prop_collection[index]: "
2509 "index %d out of range, size %d",
2510 keynum,
2511 len);
2512 }
2513 else {
2514 PyErr_Format(PyExc_RuntimeError,
2515 "bpy_prop_collection[index]: internal error, "
2516 "valid index %d given in %d sized collection, but value not found",
2517 keynum_abs,
2518 len);
2519 }
2520
2521 return nullptr;
2522}
2523
2524/* Values type must have been already checked. */
2526 Py_ssize_t keynum,
2527 PyObject *value)
2528{
2529 Py_ssize_t keynum_abs = keynum;
2530 static const PointerRNA null_ptr;
2531 const PointerRNA *ptr = (value == Py_None) ?
2532 &null_ptr :
2533 &(reinterpret_cast<BPy_StructRNA *>(value))->ptr.value();
2534
2536
2538
2539 if (!RNA_property_collection_assign_int(&self->ptr.value(), self->prop, keynum_abs, ptr)) {
2540 const int len = RNA_property_collection_length(&self->ptr.value(), self->prop);
2541 if (keynum_abs >= len) {
2542 PyErr_Format(PyExc_IndexError,
2543 "bpy_prop_collection[index] = value: "
2544 "index %d out of range, size %d",
2545 keynum,
2546 len);
2547 }
2548 else {
2549 PyErr_Format(PyExc_IndexError,
2550 "bpy_prop_collection[index] = value: "
2551 "index %d failed assignment (unknown reason)",
2552 keynum);
2553 }
2554 return -1;
2555 }
2556
2557 return 0;
2558}
2559
2560static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum)
2561{
2562 int len;
2563
2565
2567
2568 if (keynum < 0) {
2569 keynum += len;
2570 }
2571
2572 if (keynum >= 0 && keynum < len) {
2573 return pyrna_prop_array_to_py_index(self, keynum);
2574 }
2575
2576 PyErr_Format(PyExc_IndexError, "bpy_prop_array[index]: index %d out of range", keynum);
2577 return nullptr;
2578}
2579
2580static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
2581{
2582 PointerRNA newptr;
2583
2585
2587 if (RNA_property_collection_lookup_string(&self->ptr.value(), self->prop, keyname, &newptr)) {
2588 return pyrna_struct_CreatePyObject(&newptr);
2589 }
2590 }
2592 /* No callback defined, just iterate and find the nth item. */
2593 const int key_len = strlen(keyname);
2594 char name[256];
2595 int name_len;
2596 PyObject *result = nullptr;
2597 bool found = false;
2599 RNA_property_collection_begin(&self->ptr.value(), self->prop, &iter);
2600 for (; iter.valid; RNA_property_collection_next(&iter)) {
2601 PropertyRNA *nameprop = RNA_struct_name_property(iter.ptr.type);
2602 /* The #RNA_property_collection_lookup_string_has_nameprop check should account for this.
2603 * Although it's technically possible a sub-type clears the name property,
2604 * this seems unlikely. */
2605 BLI_assert(nameprop != nullptr);
2606 char *name_ptr = RNA_property_string_get_alloc(
2607 &iter.ptr, nameprop, name, sizeof(name), &name_len);
2608 if ((key_len == name_len) && STREQ(name_ptr, keyname)) {
2609 found = true;
2610 }
2611 if (name != name_ptr) {
2612 MEM_delete(name_ptr);
2613 }
2614 if (found) {
2616 break;
2617 }
2618 }
2619 /* It's important to end the iterator after `result` has been created
2620 * so iterators may optionally invalidate items that were iterated over, see: #100286. */
2622 if (found) {
2624 Py_DECREF(result);
2625 result = nullptr; /* The exception has been set. */
2626 }
2627 return result;
2628 }
2629 }
2630 else {
2631 pyrna_prop_collection_string_subscript_unsupported_error(self, "bpy_prop_collection[key]");
2632 return nullptr;
2633 }
2634
2635 PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
2636 return nullptr;
2637}
2638// static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname)
2639
2652 PyObject *key,
2653 const char *err_prefix,
2654 const short err_not_found,
2655 PointerRNA *r_ptr)
2656{
2657 const char *keyname;
2658
2659 /* First validate the args, all we know is that they are a tuple. */
2660 if (PyTuple_GET_SIZE(key) != 2) {
2661 PyErr_Format(PyExc_KeyError,
2662 "%s: tuple key must be a pair, not size %d",
2663 err_prefix,
2664 PyTuple_GET_SIZE(key));
2665 return -1;
2666 }
2667 if (self->ptr->type != RNA_BlendData) {
2668 PyErr_Format(PyExc_KeyError,
2669 "%s: is only valid for bpy.data collections, not %.200s",
2670 err_prefix,
2671 RNA_struct_identifier(self->ptr->type));
2672 return -1;
2673 }
2674 if ((keyname = PyUnicode_AsUTF8(PyTuple_GET_ITEM(key, 0))) == nullptr) {
2675 PyErr_Format(PyExc_KeyError,
2676 "%s: id must be a string, not %.200s",
2677 err_prefix,
2678 Py_TYPE(PyTuple_GET_ITEM(key, 0))->tp_name);
2679 return -1;
2680 }
2681
2682 PyObject *keylib = PyTuple_GET_ITEM(key, 1);
2683 Library *lib;
2684 bool found = false;
2685
2686 if (keylib == Py_None) {
2687 lib = nullptr;
2688 }
2689 else if (PyUnicode_Check(keylib)) {
2690 Main *bmain = static_cast<Main *>(self->ptr->data);
2691 const char *keylib_str = PyUnicode_AsUTF8(keylib);
2692 lib = static_cast<Library *>(
2693 BLI_findstring(&bmain->libraries, keylib_str, offsetof(Library, filepath)));
2694 if (lib == nullptr) {
2695 if (err_not_found) {
2696 PyErr_Format(PyExc_KeyError,
2697 "%s: lib filepath '%.1024s' "
2698 "does not reference a valid library",
2699 err_prefix,
2700 keylib_str);
2701 return -1;
2702 }
2703
2704 return 0;
2705 }
2706 }
2707 else {
2708 PyErr_Format(PyExc_KeyError,
2709 "%s: lib must be a string or None, not %.200s",
2710 err_prefix,
2711 Py_TYPE(keylib)->tp_name);
2712 return -1;
2713 }
2714
2715 /* lib is either a valid pointer or nullptr,
2716 * either way can do direct comparison with id.lib */
2717
2718 RNA_PROP_BEGIN (&self->ptr.value(), itemptr, self->prop) {
2719 ID *id = static_cast<ID *>(itemptr.data); /* Always an ID. */
2720 if (id->lib == lib && STREQLEN(keyname, id->name + 2, sizeof(id->name) - 2)) {
2721 found = true;
2722 if (r_ptr) {
2723 *r_ptr = itemptr;
2724 }
2725 break;
2726 }
2727 }
2729
2730 /* We may want to fail silently as with collection.get(). */
2731 if ((found == false) && err_not_found) {
2732 /* Only runs for getitem access so use fixed string. */
2733 PyErr_SetString(PyExc_KeyError, "bpy_prop_collection[key, lib]: not found");
2734 return -1;
2735 }
2736
2737 return found; /* 1 / 0, no exception. */
2738}
2739
2741 PyObject *key,
2742 const char *err_prefix,
2743 const bool err_not_found)
2744{
2745 PointerRNA ptr;
2747 self, key, err_prefix, err_not_found, &ptr);
2748
2749 if (contains == 1) {
2750 return pyrna_struct_CreatePyObject(&ptr);
2751 }
2752
2753 return nullptr;
2754}
2755
2757 Py_ssize_t start,
2758 Py_ssize_t stop)
2759{
2760 CollectionPropertyIterator rna_macro_iter;
2761 int count;
2762
2763 PyObject *list;
2764 PyObject *item;
2765
2767
2768 list = PyList_New(0);
2769
2770 /* Skip to start. */
2771 RNA_property_collection_begin(&self->ptr.value(), self->prop, &rna_macro_iter);
2772 RNA_property_collection_skip(&rna_macro_iter, start);
2773
2774 /* Add items until stop. */
2775 for (count = start; rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
2776 item = pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
2777 PyList_APPEND(list, item);
2778
2779 count++;
2780 if (count == stop) {
2781 break;
2782 }
2783 }
2784
2785 RNA_property_collection_end(&rna_macro_iter);
2786
2787 return list;
2788}
2789
2796 PointerRNA *ptr,
2797 PropertyRNA *prop,
2798 Py_ssize_t start,
2799 Py_ssize_t step,
2800 Py_ssize_t slice_length,
2801 Py_ssize_t array_length)
2802{
2803 Py_ssize_t count, index;
2804 int totdim;
2805 PyObject *tuple;
2806
2807 /* Isn't needed, internal use only. */
2808 // PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2809
2810 tuple = PyTuple_New(slice_length);
2811
2812 totdim = RNA_property_array_dimension(ptr, prop, nullptr);
2813
2814 if (totdim > 1) {
2815 for (count = 0, index = start; count < slice_length; count++, index += step) {
2816 PyTuple_SET_ITEM(tuple, count, pyrna_prop_array_to_py_index(self, int(index)));
2817 }
2818 }
2819 else {
2820 switch (RNA_property_type(prop)) {
2821 case PROP_FLOAT: {
2822 float values_stack[PYRNA_STACK_ARRAY];
2823 float *values;
2824 if (array_length > PYRNA_STACK_ARRAY) {
2825 values = static_cast<float *>(PyMem_MALLOC(sizeof(float) * array_length));
2826 }
2827 else {
2828 values = values_stack;
2829 }
2830 RNA_property_float_get_array(ptr, prop, values);
2831
2832 for (count = 0, index = start; count < slice_length; count++, index += step) {
2833 PyTuple_SET_ITEM(tuple, count, PyFloat_FromDouble(values[index]));
2834 }
2835
2836 if (values != values_stack) {
2837 PyMem_FREE(values);
2838 }
2839 break;
2840 }
2841 case PROP_BOOLEAN: {
2842 bool values_stack[PYRNA_STACK_ARRAY];
2843 bool *values;
2844 if (array_length > PYRNA_STACK_ARRAY) {
2845 values = static_cast<bool *>(PyMem_MALLOC(sizeof(bool) * array_length));
2846 }
2847 else {
2848 values = values_stack;
2849 }
2850
2851 RNA_property_boolean_get_array(ptr, prop, values);
2852 for (count = 0, index = start; count < slice_length; count++, index += step) {
2853 PyTuple_SET_ITEM(tuple, count, PyBool_FromLong(values[index]));
2854 }
2855
2856 if (values != values_stack) {
2857 PyMem_FREE(values);
2858 }
2859 break;
2860 }
2861 case PROP_INT: {
2862 int values_stack[PYRNA_STACK_ARRAY];
2863 int *values;
2864 if (array_length > PYRNA_STACK_ARRAY) {
2865 values = static_cast<int *>(PyMem_MALLOC(sizeof(int) * array_length));
2866 }
2867 else {
2868 values = values_stack;
2869 }
2870
2871 RNA_property_int_get_array(ptr, prop, values);
2872 for (count = 0, index = start; count < slice_length; count++, index += step) {
2873 PyTuple_SET_ITEM(tuple, count, PyLong_FromLong(values[index]));
2874 }
2875
2876 if (values != values_stack) {
2877 PyMem_FREE(values);
2878 }
2879 break;
2880 }
2881 default:
2882 BLI_assert_msg(0, "Invalid array type");
2883
2884 PyErr_SetString(PyExc_TypeError, "not an array type");
2885 Py_DECREF(tuple);
2886 tuple = nullptr;
2887 break;
2888 }
2889 }
2890 return tuple;
2891}
2892
2893static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
2894{
2896
2897 if (PyUnicode_Check(key)) {
2898 return pyrna_prop_collection_subscript_str(self, PyUnicode_AsUTF8(key));
2899 }
2900 if (PyIndex_Check(key)) {
2901 const Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2902 if (i == -1 && PyErr_Occurred()) {
2903 return nullptr;
2904 }
2905
2907 }
2908 if (PySlice_Check(key)) {
2909 PySliceObject *key_slice = reinterpret_cast<PySliceObject *>(key);
2910 Py_ssize_t step = 1;
2911
2912 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key_slice->step, &step)) {
2913 return nullptr;
2914 }
2915 if (step != 1) {
2916 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2917 return nullptr;
2918 }
2919 if (key_slice->start == Py_None && key_slice->stop == Py_None) {
2920 return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2921 }
2922
2923 Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
2924
2925 /* Avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2926 if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
2927 return nullptr;
2928 }
2929 if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
2930 return nullptr;
2931 }
2932
2933 if (start < 0 || stop < 0) {
2934 /* Only get the length for negative values. */
2935 const Py_ssize_t len = Py_ssize_t(
2936 RNA_property_collection_length(&self->ptr.value(), self->prop));
2937 if (start < 0) {
2938 start += len;
2939 CLAMP_MIN(start, 0);
2940 }
2941 if (stop < 0) {
2942 stop += len;
2943 CLAMP_MIN(stop, 0);
2944 }
2945 }
2946
2947 if (stop - start <= 0) {
2948 return PyList_New(0);
2949 }
2950
2951 return pyrna_prop_collection_subscript_slice(self, start, stop);
2952 }
2953 if (PyTuple_Check(key)) {
2954 /* Special case, for ID data-blocks. */
2956 self, key, "bpy_prop_collection[id, lib]", true);
2957 }
2958
2959 PyErr_Format(PyExc_TypeError,
2960 "bpy_prop_collection[key]: invalid key, "
2961 "must be a string or an int, not %.200s",
2962 Py_TYPE(key)->tp_name);
2963 return nullptr;
2964}
2965
2966/* generic check to see if a PyObject is compatible with a collection
2967 * -1 on failure, 0 on success, sets the error */
2968static int pyrna_prop_collection_type_check(BPy_PropertyRNA *self, PyObject *value)
2969{
2970 StructRNA *prop_srna;
2971
2972 if (value == Py_None) {
2973 if (RNA_property_flag(self->prop) & PROP_NEVER_NULL) {
2974 PyErr_SetString(PyExc_TypeError,
2975 "bpy_prop_collection[key] = value: invalid, "
2976 "this collection doesn't support None assignment");
2977 return -1;
2978 }
2979
2980 return 0; /* None is OK. */
2981 }
2982 if (BPy_StructRNA_Check(value) == 0) {
2983 PyErr_Format(PyExc_TypeError,
2984 "bpy_prop_collection[key] = value: invalid, "
2985 "expected a StructRNA type or None, not a %.200s",
2986 Py_TYPE(value)->tp_name);
2987 return -1;
2988 }
2989 if ((prop_srna = RNA_property_pointer_type(&self->ptr.value(), self->prop))) {
2990 StructRNA *value_srna = (reinterpret_cast<BPy_StructRNA *>(value))->ptr->type;
2991 if (RNA_struct_is_a(value_srna, prop_srna) == 0) {
2992 PyErr_Format(PyExc_TypeError,
2993 "bpy_prop_collection[key] = value: invalid, "
2994 "expected a '%.200s' type or None, not a '%.200s'",
2995 RNA_struct_identifier(prop_srna),
2996 RNA_struct_identifier(value_srna));
2997 return -1;
2998 }
2999
3000 return 0; /* OK, this is the correct type! */
3001 }
3002
3003 PyErr_SetString(PyExc_TypeError,
3004 "bpy_prop_collection[key] = value: internal error, "
3005 "failed to get the collection type");
3006 return -1;
3007}
3008
3009/* NOTE: currently this is a copy of 'pyrna_prop_collection_subscript' with
3010 * large blocks commented, we may support slice/key indices later */
3012 PyObject *key,
3013 PyObject *value)
3014{
3016
3017 /* Validate the assigned value. */
3018 if (value == nullptr) {
3019 PyErr_SetString(PyExc_TypeError, "del bpy_prop_collection[key]: not supported");
3020 return -1;
3021 }
3022 if (pyrna_prop_collection_type_check(self, value) == -1) {
3023 return -1; /* Exception is set. */
3024 }
3025
3026#if 0
3027 if (PyUnicode_Check(key)) {
3028 return pyrna_prop_collection_subscript_str(self, PyUnicode_AsUTF8(key));
3029 }
3030 else
3031#endif
3032 if (PyIndex_Check(key)) {
3033 const Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
3034 if (i == -1 && PyErr_Occurred()) {
3035 return -1;
3036 }
3037
3038 return pyrna_prop_collection_ass_subscript_int(self, i, value);
3039 }
3040#if 0 /* TODO: fake slice assignment. */
3041 else if (PySlice_Check(key)) {
3042 PySliceObject *key_slice = (PySliceObject *)key;
3043 Py_ssize_t step = 1;
3044
3045 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key_slice->step, &step)) {
3046 return nullptr;
3047 }
3048 else if (step != 1) {
3049 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
3050 return nullptr;
3051 }
3052 else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
3053 return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
3054 }
3055 else {
3056 Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
3057
3058 /* Avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
3059 if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) {
3060 return nullptr;
3061 }
3062 if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) {
3063 return nullptr;
3064 }
3065
3066 if (start < 0 || stop < 0) {
3067 /* Only get the length for negative values. */
3068 Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr.value(), self->prop);
3069 if (start < 0) {
3070 start += len;
3071 CLAMP_MIN(start, 0);
3072 }
3073 if (stop < 0) {
3074 stop += len;
3075 CLAMP_MIN(stop, 0);
3076 }
3077 }
3078
3079 if (stop - start <= 0) {
3080 return PyList_New(0);
3081 }
3082 else {
3083 return pyrna_prop_collection_subscript_slice(self, start, stop);
3084 }
3085 }
3086 }
3087#endif
3088
3089 PyErr_Format(PyExc_TypeError,
3090 "bpy_prop_collection[key]: invalid key, "
3091 "must be an int, not %.200s",
3092 Py_TYPE(key)->tp_name);
3093 return -1;
3094}
3095
3096static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
3097{
3099
3100#if 0
3101 if (PyUnicode_Check(key)) {
3102 return pyrna_prop_array_subscript_str(self, PyUnicode_AsUTF8(key));
3103 }
3104 else
3105#endif
3106 if (PyIndex_Check(key)) {
3107 const Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
3108 if (i == -1 && PyErr_Occurred()) {
3109 return nullptr;
3110 }
3111 return pyrna_prop_array_subscript_int(self, i);
3112 }
3113 if (PySlice_Check(key)) {
3114 const Py_ssize_t len = pyrna_prop_array_length(self);
3115 Py_ssize_t start, stop, step, slice_length;
3116
3117 if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slice_length) < 0) {
3118 return nullptr;
3119 }
3120
3121 if (slice_length <= 0) {
3122 return PyTuple_New(0);
3123 }
3124
3126 self, &self->ptr.value(), self->prop, start, step, slice_length, len);
3127 }
3128
3129 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
3130 return nullptr;
3131}
3132
3136
3137static PyObject *prop_subscript_ass_array_slice__as_seq_fast(PyObject *value, int length)
3138{
3139 PyObject *value_fast;
3140 if (!(value_fast = PySequence_Fast(value,
3141 "bpy_prop_array[slice] = value: "
3142 "element in assignment is not a sequence type")))
3143 {
3144 return nullptr;
3145 }
3146 if (PySequence_Fast_GET_SIZE(value_fast) != length) {
3147 Py_DECREF(value_fast);
3148 PyErr_SetString(PyExc_ValueError,
3149 "bpy_prop_array[slice] = value: "
3150 "re-sizing bpy_struct element in arrays isn't supported");
3151 return nullptr;
3152 }
3153
3154 return value_fast;
3155}
3156
3158 PyObject **value_items, float *value, int totdim, const int dimsize[], const float range[2])
3159{
3160 const int length = dimsize[0];
3161 if (totdim > 1) {
3162 int index = 0;
3163 int i;
3164 for (i = 0; i != length; i++) {
3165 PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
3166 if (subvalue == nullptr) [[unlikely]] {
3167 return 0;
3168 }
3169
3171 PySequence_Fast_ITEMS(subvalue), &value[index], totdim - 1, &dimsize[1], range);
3172
3173 Py_DECREF(subvalue);
3174 }
3175 return index;
3176 }
3177
3178 BLI_assert(totdim == 1);
3179 const float min = range[0], max = range[1];
3180 int i;
3181 for (i = 0; i != length; i++) {
3182 float v = PyFloat_AsDouble(value_items[i]);
3183 CLAMP(v, min, max);
3184 value[i] = v;
3185 }
3186 return i;
3187}
3188
3190 PyObject **value_items, int *value, int totdim, const int dimsize[], const int range[2])
3191{
3192 const int length = dimsize[0];
3193 if (totdim > 1) {
3194 int index = 0;
3195 int i;
3196 for (i = 0; i != length; i++) {
3197 PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
3198 if (subvalue == nullptr) [[unlikely]] {
3199 return 0;
3200 }
3201
3203 PySequence_Fast_ITEMS(subvalue), &value[index], totdim - 1, &dimsize[1], range);
3204
3205 Py_DECREF(subvalue);
3206 }
3207 return index;
3208 }
3209
3210 BLI_assert(totdim == 1);
3211 const int min = range[0], max = range[1];
3212 int i;
3213 for (i = 0; i != length; i++) {
3214 int v = PyLong_AsLong(value_items[i]);
3215 CLAMP(v, min, max);
3216 value[i] = v;
3217 }
3218 return i;
3219}
3220
3221static int prop_subscript_ass_array_slice__bool_recursive(PyObject **value_items,
3222 bool *value,
3223 int totdim,
3224 const int dimsize[])
3225{
3226 const int length = dimsize[0];
3227 if (totdim > 1) {
3228 int index = 0;
3229 int i;
3230 for (i = 0; i != length; i++) {
3231 PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
3232 if (subvalue == nullptr) [[unlikely]] {
3233 return 0;
3234 }
3235
3237 PySequence_Fast_ITEMS(subvalue), &value[index], totdim - 1, &dimsize[1]);
3238
3239 Py_DECREF(subvalue);
3240 }
3241 return index;
3242 }
3243
3244 BLI_assert(totdim == 1);
3245 int i;
3246 for (i = 0; i != length; i++) {
3247 const int v = PyLong_AsLong(value_items[i]);
3248 value[i] = v;
3249 }
3250 return i;
3251}
3252
3253/* Could call `pyrna_py_to_prop_array_index(self, i, value)` in a loop, but it is slow. */
3255 PropertyRNA *prop,
3256 int arraydim,
3257 int arrayoffset,
3258 int start,
3259 int step,
3260 int slice_length,
3261 int array_length,
3262 PyObject *value_orig)
3263{
3264 /* For `step == 1` the targeted chunks are contiguous in memory,
3265 * so a single recursive call with `dimsize[arraydim] = slice_length` writes the whole range
3266 * in one descent. Otherwise each chunk is written individually with `dimsize[arraydim] = 1`,
3267 * stepping the destination by `step * span` between calls.
3268 *
3269 * The asymmetry vs. the read counterpart `pyrna_prop_array_subscript_slice`
3270 * is intentional - read has no recursive helper to amortize,
3271 * so its loop is already minimal. */
3272
3273 const int length_flat = RNA_property_array_length(ptr, prop);
3274 PyObject *value;
3275 void *values_alloc = nullptr;
3276 int ret = 0;
3277
3278 if (value_orig == nullptr) {
3279 PyErr_SetString(
3280 PyExc_TypeError,
3281 "bpy_prop_array[slice] = value: deleting with list types is not supported by bpy_struct");
3282 return -1;
3283 }
3284
3285 if (!(value = PySequence_Fast(
3286 value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type")))
3287 {
3288 return -1;
3289 }
3290
3291 if (PySequence_Fast_GET_SIZE(value) != slice_length) {
3292 Py_DECREF(value);
3293 PyErr_SetString(PyExc_TypeError,
3294 "bpy_prop_array[slice] = value: re-sizing bpy_struct arrays isn't supported");
3295 return -1;
3296 }
3297
3298 int dimsize[3];
3299 const int totdim = RNA_property_array_dimension(ptr, prop, dimsize);
3300 if (totdim > 1) {
3301 BLI_assert(dimsize[arraydim] == array_length);
3302 }
3303
3304 int span = 1;
3305 if (totdim > 1) {
3306 for (int i = arraydim + 1; i < totdim; i++) {
3307 span *= dimsize[i];
3308 }
3309 }
3310
3311 /* Assigning a subset of the whole array.
3312 *
3313 * RNA can only set a property's full array, so for any partial assignment we must first read the
3314 * existing array into `values`, mutate the targeted positions, then write the whole array back.
3315 *
3316 * The pre-read is only safe to skip when every position in the backing
3317 * array is overwritten by the loop below, which requires:
3318 * - `slice_length == length`: the slice covers every index of this dimension
3319 * (only possible when step is +1 or -1),
3320 * - `arraydim == 0` and `arrayoffset == 0`: this is the top of the backing array, not a
3321 * sub-array view (in which case the surrounding positions belong to other dimensions).
3322 */
3323 const bool is_subset = (slice_length != array_length) || (arrayoffset != 0) || (arraydim != 0);
3324
3325 PyObject **value_items = PySequence_Fast_ITEMS(value);
3326 switch (RNA_property_type(prop)) {
3327 case PROP_FLOAT: {
3328 float values_stack[PYRNA_STACK_ARRAY];
3329 float *values = static_cast<float *>(
3330 (length_flat > PYRNA_STACK_ARRAY) ?
3331 (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) :
3332 values_stack);
3333 if (is_subset) {
3334 RNA_property_float_get_array(ptr, prop, values);
3335 }
3336
3337 float range[2];
3338 RNA_property_float_range(ptr, prop, &range[0], &range[1]);
3339
3340 if (step == 1) {
3341 dimsize[arraydim] = slice_length;
3343 &values[arrayoffset + (start * span)],
3344 totdim - arraydim,
3345 &dimsize[arraydim],
3346 range);
3347 }
3348 else {
3349 dimsize[arraydim] = 1;
3350 for (int i = 0; i < slice_length; i++) {
3352 value_items + i,
3353 &values[arrayoffset + ((start + (i * step)) * span)],
3354 totdim - arraydim,
3355 &dimsize[arraydim],
3356 range);
3357 if (PyErr_Occurred()) {
3358 break;
3359 }
3360 }
3361 }
3362
3363 if (PyErr_Occurred()) {
3364 ret = -1;
3365 }
3366 else {
3367 RNA_property_float_set_array(ptr, prop, values);
3368 }
3369 break;
3370 }
3371 case PROP_INT: {
3372 int values_stack[PYRNA_STACK_ARRAY];
3373 int *values = static_cast<int *>(
3374 (length_flat > PYRNA_STACK_ARRAY) ?
3375 (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) :
3376 values_stack);
3377 if (is_subset) {
3378 RNA_property_int_get_array(ptr, prop, values);
3379 }
3380
3381 int range[2];
3382 RNA_property_int_range(ptr, prop, &range[0], &range[1]);
3383
3384 if (step == 1) {
3385 dimsize[arraydim] = slice_length;
3387 &values[arrayoffset + (start * span)],
3388 totdim - arraydim,
3389 &dimsize[arraydim],
3390 range);
3391 }
3392 else {
3393 dimsize[arraydim] = 1;
3394 for (int i = 0; i < slice_length; i++) {
3396 value_items + i,
3397 &values[arrayoffset + ((start + (i * step)) * span)],
3398 totdim - arraydim,
3399 &dimsize[arraydim],
3400 range);
3401 if (PyErr_Occurred()) {
3402 break;
3403 }
3404 }
3405 }
3406
3407 if (PyErr_Occurred()) {
3408 ret = -1;
3409 }
3410 else {
3411 RNA_property_int_set_array(ptr, prop, values);
3412 }
3413 break;
3414 }
3415 case PROP_BOOLEAN: {
3416 bool values_stack[PYRNA_STACK_ARRAY];
3417 bool *values = static_cast<bool *>(
3418 (length_flat > PYRNA_STACK_ARRAY) ?
3419 (values_alloc = PyMem_MALLOC(sizeof(bool) * length_flat)) :
3420 values_stack);
3421
3422 if (is_subset) {
3423 RNA_property_boolean_get_array(ptr, prop, values);
3424 }
3425
3426 if (step == 1) {
3427 dimsize[arraydim] = slice_length;
3429 &values[arrayoffset + (start * span)],
3430 totdim - arraydim,
3431 &dimsize[arraydim]);
3432 }
3433 else {
3434 dimsize[arraydim] = 1;
3435 for (int i = 0; i < slice_length; i++) {
3437 value_items + i,
3438 &values[arrayoffset + ((start + (i * step)) * span)],
3439 totdim - arraydim,
3440 &dimsize[arraydim]);
3441 if (PyErr_Occurred()) {
3442 break;
3443 }
3444 }
3445 }
3446
3447 if (PyErr_Occurred()) {
3448 ret = -1;
3449 }
3450 else {
3451 RNA_property_boolean_set_array(ptr, prop, values);
3452 }
3453 break;
3454 }
3455 default:
3456 PyErr_SetString(PyExc_TypeError, "not an array type");
3457 ret = -1;
3458 break;
3459 }
3460
3461 Py_DECREF(value);
3462
3463 if (values_alloc) {
3464 PyMem_FREE(values_alloc);
3465 }
3466
3467 return ret;
3468}
3469
3471 Py_ssize_t keynum,
3472 PyObject *value)
3473{
3475
3476 int len = pyrna_prop_array_length(self);
3477
3478 if (keynum < 0) {
3479 keynum += len;
3480 }
3481
3482 if (keynum >= 0 && keynum < len) {
3483 return pyrna_py_to_prop_array_index(self, keynum, value);
3484 }
3485
3486 PyErr_SetString(PyExc_IndexError, "bpy_prop_array[index] = value: index out of range");
3487 return -1;
3488}
3489
3491 PyObject *key,
3492 PyObject *value)
3493{
3494 // char *keyname = nullptr; /* Not supported yet. */
3495 int ret = -1;
3496
3498
3499 if (!RNA_property_editable_flag(&self->ptr.value(), self->prop)) {
3500 PyErr_Format(PyExc_AttributeError,
3501 "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
3503 RNA_struct_identifier(self->ptr->type));
3504 ret = -1;
3505 }
3506
3507 else if (PyIndex_Check(key)) {
3508 const Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
3509 if (i == -1 && PyErr_Occurred()) {
3510 ret = -1;
3511 }
3512 else {
3513 ret = prop_subscript_ass_array_int(self, i, value);
3514 }
3515 }
3516 else if (PySlice_Check(key)) {
3517 const Py_ssize_t len = pyrna_prop_array_length(self);
3518 Py_ssize_t start, stop, step, slice_length;
3519
3520 if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slice_length) < 0) {
3521 ret = -1;
3522 }
3523 else if (slice_length <= 0) {
3524 ret = 0; /* Do nothing. */
3525 }
3526 else {
3527 ret = prop_subscript_ass_array_slice(&self->ptr.value(),
3528 self->prop,
3529 self->arraydim,
3530 self->arrayoffset,
3531 start,
3532 step,
3533 slice_length,
3534 len,
3535 value);
3536 }
3537 }
3538 else {
3539 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
3540 ret = -1;
3541 }
3542
3543 if (ret != -1) {
3544 if (RNA_property_update_check(self->prop)) {
3545 RNA_property_update(BPY_context_get(), &self->ptr.value(), self->prop);
3546 }
3547 }
3548
3549 return ret;
3550}
3551
3552/* For slice only. */
3553static PyMappingMethods pyrna_prop_array_as_mapping = {
3554 /*mp_length*/ reinterpret_cast<lenfunc>(pyrna_prop_array_length),
3555 /*mp_subscript*/ reinterpret_cast<binaryfunc>(pyrna_prop_array_subscript),
3556 /*mp_ass_subscript*/ reinterpret_cast<objobjargproc>(pyrna_prop_array_ass_subscript),
3557};
3558
3559static PyMappingMethods pyrna_prop_collection_as_mapping = {
3560 /*mp_length*/ reinterpret_cast<lenfunc>(pyrna_prop_collection_length),
3561 /*mp_subscript*/ reinterpret_cast<binaryfunc>(pyrna_prop_collection_subscript),
3562 /*mp_ass_subscript*/ reinterpret_cast<objobjargproc>(pyrna_prop_collection_ass_subscript),
3563};
3564
3565/* Only for fast bool's, large structs, assign nb_bool on init. */
3566static PyNumberMethods pyrna_prop_array_as_number = {
3567 /*nb_add*/ nullptr,
3568 /*nb_subtract*/ nullptr,
3569 /*nb_multiply*/ nullptr,
3570 /*nb_remainder*/ nullptr,
3571 /*nb_divmod*/ nullptr,
3572 /*nb_power*/ nullptr,
3573 /*nb_negative*/ nullptr,
3574 /*nb_positive*/ nullptr,
3575 /*nb_absolute*/ nullptr,
3576 /*nb_bool*/ reinterpret_cast<inquiry>(pyrna_prop_array_bool),
3577};
3578static PyNumberMethods pyrna_prop_collection_as_number = {
3579 /*nb_add*/ nullptr,
3580 /*nb_subtract*/ nullptr,
3581 /*nb_multiply*/ nullptr,
3582 /*nb_remainder*/ nullptr,
3583 /*nb_divmod*/ nullptr,
3584 /*nb_power*/ nullptr,
3585 /*nb_negative*/ nullptr,
3586 /*nb_positive*/ nullptr,
3587 /*nb_absolute*/ nullptr,
3588 /*nb_bool*/ reinterpret_cast<inquiry>(pyrna_prop_collection_bool),
3589 /*nb_invert*/ nullptr,
3590 /*nb_lshift*/ nullptr,
3591 /*nb_rshift*/ nullptr,
3592 /*nb_and*/ nullptr,
3593 /*nb_xor*/ nullptr,
3594 /*nb_or*/ nullptr,
3595 /*nb_int*/ nullptr,
3596 /*nb_reserved*/ nullptr,
3597 /*nb_float*/ nullptr,
3598 /*nb_inplace_add*/ nullptr,
3599 /*nb_inplace_subtract*/ nullptr,
3600 /*nb_inplace_multiply*/ nullptr,
3601 /*nb_inplace_remainder*/ nullptr,
3602 /*nb_inplace_power*/ nullptr,
3603 /*nb_inplace_lshift*/ nullptr,
3604 /*nb_inplace_rshift*/ nullptr,
3605 /*nb_inplace_and*/ nullptr,
3606 /*nb_inplace_xor*/ nullptr,
3607 /*nb_inplace_or*/ nullptr,
3608 /*nb_floor_divide*/ nullptr,
3609 /*nb_true_divide*/ nullptr,
3610 /*nb_inplace_floor_divide*/ nullptr,
3611 /*nb_inplace_true_divide*/ nullptr,
3612 /*nb_index*/ nullptr,
3613 /*nb_matrix_multiply*/ nullptr,
3614 /*nb_inplace_matrix_multiply*/ nullptr,
3615};
3616
3617static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
3618{
3619 return pyrna_array_contains_py(&self->ptr.value(), self->prop, value);
3620}
3621
3622static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *key)
3623{
3624 PointerRNA newptr; /* Not used, just so RNA_property_collection_lookup_string runs. */
3625
3626 if (PyTuple_Check(key)) {
3627 /* Special case, for ID data-blocks. */
3629 self, key, "(id, lib) in bpy_prop_collection", false, nullptr);
3630 }
3631
3632 /* Key in dict style check. */
3633 const char *keyname = PyUnicode_AsUTF8(key);
3634
3635 if (keyname == nullptr) {
3636 PyErr_SetString(PyExc_TypeError,
3637 "bpy_prop_collection.__contains__: expected a string or a tuple of strings");
3638 return -1;
3639 }
3640
3641 if (RNA_property_collection_lookup_string(&self->ptr.value(), self->prop, keyname, &newptr)) {
3642 return 1;
3643 }
3645 self, "bpy_prop_collection.__contains__") == -1)
3646 {
3647 return -1;
3648 }
3649
3650 return 0;
3651}
3652
3653static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
3654{
3655 const char *name = PyUnicode_AsUTF8(value);
3656
3658
3659 if (!name) {
3660 PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
3661 return -1;
3662 }
3663
3664 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
3665 PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
3666 return -1;
3667 }
3668
3669 IDProperty *group = RNA_struct_idprops(&self->ptr.value(), false);
3670
3671 if (!group) {
3672 return 0;
3673 }
3674
3675 return IDP_GetPropertyFromGroup(group, name) ? 1 : 0;
3676}
3677
3678static PySequenceMethods pyrna_prop_array_as_sequence = {
3679 /*sq_length*/ reinterpret_cast<lenfunc>(pyrna_prop_array_length),
3680 /*sq_concat*/ nullptr,
3681 /*sq_repeat*/ nullptr,
3682 /* Only set this so `PySequence_Check()` returns True. */
3683 /*sq_item*/ reinterpret_cast<ssizeargfunc>(pyrna_prop_array_subscript_int),
3684 /*was_sq_slice*/ nullptr, /* DEPRECATED. */
3685 /*sq_ass_item*/ reinterpret_cast<ssizeobjargproc>(prop_subscript_ass_array_int),
3686 /*was_sq_ass_slice*/ nullptr, /* DEPRECATED. */
3687 /*sq_contains*/ reinterpret_cast<objobjproc>(pyrna_prop_array_contains),
3688 /*sq_inplace_concat*/ nullptr,
3689 /*sq_inplace_repeat*/ nullptr,
3690};
3691
3692static PySequenceMethods pyrna_prop_collection_as_sequence = {
3693 /*sq_length*/ reinterpret_cast<lenfunc>(pyrna_prop_collection_length),
3694 /*sq_concat*/ nullptr,
3695 /*sq_repeat*/ nullptr,
3696 /* Only set this so PySequence_Check() returns True */
3697 /*sq_item*/ reinterpret_cast<ssizeargfunc>(pyrna_prop_collection_subscript_int),
3698 /*was_sq_slice*/ nullptr, /* DEPRECATED. */
3699 /* Let mapping take this one: #pyrna_prop_collection_ass_subscript_int */
3700 /*sq_ass_item*/ nullptr,
3701 /*was_sq_ass_slice*/ nullptr, /* DEPRECATED. */
3702 /*sq_contains*/ reinterpret_cast<objobjproc>(pyrna_prop_collection_contains),
3703 /*sq_inplace_concat*/ nullptr,
3704 /*sq_inplace_repeat*/ nullptr,
3705};
3706
3707static PySequenceMethods pyrna_struct_as_sequence = {
3708 /*sq_length*/ nullptr, /* Can't set the len otherwise it can evaluate as false */
3709 /*sq_concat*/ nullptr,
3710 /*sq_repeat*/ nullptr,
3711 /* Only set this so `PySequence_Check()` returns True. */
3712 /*sq_item*/ nullptr,
3713 /*was_sq_slice*/ nullptr, /* DEPRECATED. */
3714 /*sq_ass_item*/ nullptr,
3715 /*was_sq_ass_slice*/ nullptr, /* DEPRECATED. */
3716 /*sq_contains*/ reinterpret_cast<objobjproc>(pyrna_struct_contains),
3717 /*sq_inplace_concat*/ nullptr,
3718 /*sq_inplace_repeat*/ nullptr,
3719};
3720
3721static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
3722{
3723 /* Mostly copied from BPy_IDGroup_Map_GetItem. */
3724 const char *name = PyUnicode_AsUTF8(key);
3725
3727
3728 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
3729 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
3730 return nullptr;
3731 }
3732
3733 if (name == nullptr) {
3734 PyErr_SetString(PyExc_TypeError,
3735 "bpy_struct[key]: only strings are allowed as keys of ID properties");
3736 return nullptr;
3737 }
3738
3739 IDProperty *group = RNA_struct_idprops(&self->ptr.value(), false);
3740
3741 if (group == nullptr) {
3742 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
3743 return nullptr;
3744 }
3745
3747
3748 if (idprop == nullptr) {
3749 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
3750 return nullptr;
3751 }
3752
3753 return BPy_IDGroup_WrapData(self->ptr->owner_id, idprop, group);
3754}
3755
3756static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
3757{
3759
3760 IDProperty *group = RNA_struct_idprops(&self->ptr.value(), true);
3761
3762#ifdef USE_PEDANTIC_WRITE
3763 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), key)) {
3764 return -1;
3765 }
3766#endif /* USE_PEDANTIC_WRITE */
3767
3768 if (group == nullptr) {
3769 PyErr_SetString(PyExc_TypeError,
3770 "bpy_struct[key] = val: id properties not supported for this type");
3771 return -1;
3772 }
3773
3774 if (value && BPy_StructRNA_Check(value)) {
3775 BPy_StructRNA *val = reinterpret_cast<BPy_StructRNA *>(value);
3776 if (val && self->ptr->type && val->ptr->type) {
3777 if (!RNA_struct_idprops_datablock_allowed(self->ptr->type) &&
3779 {
3780 PyErr_SetString(
3781 PyExc_TypeError,
3782 "bpy_struct[key] = val: data-block id properties not supported for this type");
3783 return -1;
3784 }
3785 }
3786 }
3787
3788 return BPy_Wrap_SetMapItem(group, key, value);
3789}
3790
3791static PyMappingMethods pyrna_struct_as_mapping = {
3792 /*mp_length*/ static_cast<lenfunc>(nullptr),
3793 /*mp_subscript*/ reinterpret_cast<binaryfunc>(pyrna_struct_subscript),
3794 /*mp_ass_subscript*/ reinterpret_cast<objobjargproc>(pyrna_struct_ass_subscript),
3795};
3796
3798 /* Wrap. */
3799 pyrna_struct_keys_doc,
3800 ".. method:: keys()\n"
3801 "\n"
3802 " Returns the keys of this objects custom properties (matches Python's\n"
3803 " dictionary function of the same name).\n"
3804 "\n"
3805 " :return: custom property keys.\n"
3806 " :rtype: :class:`idprop.types.IDPropertyGroupViewKeys`\n"
3808static PyObject *pyrna_struct_keys(BPy_StructRNA *self)
3809{
3811
3812 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
3813 PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
3814 return nullptr;
3815 }
3816
3817 /* `group` may be nullptr. */
3818 IDProperty *group = RNA_struct_idprops(&self->ptr.value(), false);
3819 return BPy_Wrap_GetKeys_View_WithID(self->ptr->owner_id, group);
3820}
3821
3823 /* Wrap. */
3824 pyrna_struct_items_doc,
3825 ".. method:: items()\n"
3826 "\n"
3827 " Returns the items of this objects custom properties (matches Python's\n"
3828 " dictionary function of the same name).\n"
3829 "\n"
3830 " :return: custom property key, value pairs.\n"
3831 " :rtype: :class:`idprop.types.IDPropertyGroupViewItems`\n"
3833static PyObject *pyrna_struct_items(BPy_StructRNA *self)
3834{
3836
3837 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
3838 PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
3839 return nullptr;
3840 }
3841
3842 /* `group` may be nullptr. */
3843 IDProperty *group = RNA_struct_idprops(&self->ptr.value(), false);
3844 return BPy_Wrap_GetItems_View_WithID(self->ptr->owner_id, group);
3845}
3846
3848 /* Wrap. */
3849 pyrna_struct_values_doc,
3850 ".. method:: values()\n"
3851 "\n"
3852 " Returns the values of this objects custom properties (matches Python's\n"
3853 " dictionary function of the same name).\n"
3854 "\n"
3855 " :return: custom property values.\n"
3856 " :rtype: :class:`idprop.types.IDPropertyGroupViewValues`\n"
3858static PyObject *pyrna_struct_values(BPy_StructRNA *self)
3859{
3861
3862 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
3863 PyErr_SetString(PyExc_TypeError,
3864 "bpy_struct.values(): this type doesn't support IDProperties");
3865 return nullptr;
3866 }
3867
3868 /* `group` may be nullptr. */
3869 IDProperty *group = RNA_struct_idprops(&self->ptr.value(), false);
3870 return BPy_Wrap_GetValues_View_WithID(self->ptr->owner_id, group);
3871}
3872
3874 /* Wrap. */
3875 pyrna_struct_is_property_set_doc,
3876 ".. method:: is_property_set(property, /, *, ghost=True)\n"
3877 "\n"
3878 " Check if a property is set, use for testing operator properties.\n"
3879 "\n"
3880 " :param property: Property name.\n"
3881 " :type property: str\n"
3882 " :param ghost: Used for operators that re-run with previous settings.\n"
3883 " In this case the property is not marked as set,\n"
3884 " yet the value from the previous execution is used.\n"
3885 "\n"
3886 " In rare cases you may want to set this option to false.\n"
3887 "\n"
3888 " :type ghost: bool\n"
3889 " :return: True when the property has been set.\n"
3890 " :rtype: bool\n");
3891static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args, PyObject *kw)
3892{
3893 PropertyRNA *prop;
3894 const char *name;
3895 bool use_ghost = true;
3896
3898
3899 static const char *_keywords[] = {"", "ghost", nullptr};
3900 static _PyArg_Parser _parser = {
3901 "s" /* `name` (positional). */
3902 "|$" /* Optional, keyword only arguments. */
3903 "O&" /* `ghost` */
3904 ":is_property_set",
3905 _keywords,
3906 nullptr,
3907 };
3908 if (!_PyArg_ParseTupleAndKeywordsFast(args, kw, &_parser, &name, PyC_ParseBool, &use_ghost)) {
3909 return nullptr;
3910 }
3911
3912 if ((prop = RNA_struct_find_property(&self->ptr.value(), name)) == nullptr) {
3913 PyErr_Format(PyExc_TypeError,
3914 "%.200s.is_property_set(\"%.200s\") not found",
3915 RNA_struct_identifier(self->ptr->type),
3916 name);
3917 return nullptr;
3918 }
3919
3920 return PyBool_FromLong(RNA_property_is_set_ex(&self->ptr.value(), prop, use_ghost));
3921}
3922
3924 /* Wrap. */
3925 pyrna_struct_property_unset_doc,
3926 ".. method:: property_unset(property, /)\n"
3927 "\n"
3928 " Unset a property, will use default value afterward.\n"
3929 "\n"
3930 " :param property: Property name.\n"
3931 " :type property: str\n");
3932static PyObject *pyrna_struct_property_unset(BPy_StructRNA *self, PyObject *args)
3933{
3934 PropertyRNA *prop;
3935 const char *name;
3936
3938
3939 if (!PyArg_ParseTuple(args,
3940 "s" /* `property` */
3941 ":property_unset",
3942 &name))
3943 {
3944 return nullptr;
3945 }
3946
3947 if ((prop = RNA_struct_find_property(&self->ptr.value(), name)) == nullptr) {
3948 PyErr_Format(PyExc_TypeError,
3949 "%.200s.property_unset(\"%.200s\") not found",
3950 RNA_struct_identifier(self->ptr->type),
3951 name);
3952 return nullptr;
3953 }
3954
3955 RNA_property_unset(&self->ptr.value(), prop);
3956
3957 Py_RETURN_NONE;
3958}
3959
3961 /* Wrap. */
3962 pyrna_struct_is_property_hidden_doc,
3963 ".. method:: is_property_hidden(property, /)\n"
3964 "\n"
3965 " Check if a property is hidden.\n"
3966 "\n"
3967 " :param property: Property name.\n"
3968 " :type property: str\n"
3969 " :return: True when the property is hidden.\n"
3970 " :rtype: bool\n");
3971static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
3972{
3973 PropertyRNA *prop;
3974 const char *name;
3975
3977
3978 if (!PyArg_ParseTuple(args,
3979 "s" /* `property` */
3980 ":is_property_hidden",
3981 &name))
3982 {
3983 return nullptr;
3984 }
3985
3986 if ((prop = RNA_struct_find_property(&self->ptr.value(), name)) == nullptr) {
3987 PyErr_Format(PyExc_TypeError,
3988 "%.200s.is_property_hidden(\"%.200s\") not found",
3989 RNA_struct_identifier(self->ptr->type),
3990 name);
3991 return nullptr;
3992 }
3993
3994 return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
3995}
3996
3998 /* Wrap. */
3999 pyrna_struct_is_property_readonly_doc,
4000 ".. method:: is_property_readonly(property, /)\n"
4001 "\n"
4002 " Check if a property is readonly.\n"
4003 "\n"
4004 " :param property: Property name.\n"
4005 " :type property: str\n"
4006 " :return: True when the property is readonly (not writable).\n"
4007 " :rtype: bool\n");
4008static PyObject *pyrna_struct_is_property_readonly(BPy_StructRNA *self, PyObject *args)
4009{
4010 PropertyRNA *prop;
4011 const char *name;
4012
4014
4015 if (!PyArg_ParseTuple(args,
4016 "s" /* `property` */
4017 ":is_property_readonly",
4018 &name))
4019 {
4020 return nullptr;
4021 }
4022
4023 if ((prop = RNA_struct_find_property(&self->ptr.value(), name)) == nullptr) {
4024 PyErr_Format(PyExc_TypeError,
4025 "%.200s.is_property_readonly(\"%.200s\") not found",
4026 RNA_struct_identifier(self->ptr->type),
4027 name);
4028 return nullptr;
4029 }
4030
4031 return PyBool_FromLong(!RNA_property_editable(&self->ptr.value(), prop));
4032}
4033
4035 /* Wrap. */
4036 pyrna_struct_is_property_overridable_library_doc,
4037 ".. method:: is_property_overridable_library(property, /)\n"
4038 "\n"
4039 " Check if a property is overridable.\n"
4040 "\n"
4041 " :param property: Property name.\n"
4042 " :type property: str\n"
4043 " :return: True when the property is overridable.\n"
4044 " :rtype: bool\n");
4046{
4047 PropertyRNA *prop;
4048 const char *name;
4049
4051
4052 if (!PyArg_ParseTuple(args,
4053 "s" /* `property` */
4054 ":is_property_overridable_library",
4055 &name))
4056 {
4057 return nullptr;
4058 }
4059
4060 if ((prop = RNA_struct_find_property(&self->ptr.value(), name)) == nullptr) {
4061 PyErr_Format(PyExc_TypeError,
4062 "%.200s.is_property_overridable_library(\"%.200s\") not found",
4063 RNA_struct_identifier(self->ptr->type),
4064 name);
4065 return nullptr;
4066 }
4067
4068 return PyBool_FromLong(long(RNA_property_overridable_get(&self->ptr.value(), prop)));
4069}
4070
4072 /* Wrap. */
4073 pyrna_struct_property_overridable_library_set_doc,
4074 ".. method:: property_overridable_library_set(property, overridable, /)\n"
4075 "\n"
4076 " Define a property as overridable or not (only for custom properties!).\n"
4077 "\n"
4078 " :param property: Property name.\n"
4079 " :type property: str\n"
4080 " :param overridable: Overridable status to set.\n"
4081 " :type overridable: bool\n"
4082 " :return: True when the overridable status of the property was successfully set.\n"
4083 " :rtype: bool\n");
4085{
4086 PropertyRNA *prop;
4087 const char *name;
4088 int is_overridable;
4089
4091
4092 if (!PyArg_ParseTuple(args,
4093 "s" /* `property` */
4094 "p" /* `overridable` */
4095 ":property_overridable_library_set",
4096 &name,
4097 &is_overridable))
4098 {
4099 return nullptr;
4100 }
4101
4102 if ((prop = RNA_struct_find_property(&self->ptr.value(), name)) == nullptr) {
4103 PyErr_Format(PyExc_TypeError,
4104 "%.200s.property_overridable_library_set(\"%.200s\") not found",
4105 RNA_struct_identifier(self->ptr->type),
4106 name);
4107 return nullptr;
4108 }
4109
4110 return PyBool_FromLong(
4111 long(RNA_property_overridable_library_set(&self->ptr.value(), prop, bool(is_overridable))));
4112}
4113
4115 /* Wrap. */
4116 pyrna_struct_path_resolve_doc,
4117 ".. method:: path_resolve(path, coerce=True, /)\n"
4118 "\n"
4119 " Returns the property from the path, raise an exception when not found.\n"
4120 "\n"
4121 " :param path: path which this property resolves.\n"
4122 " :type path: str\n"
4123 " :param coerce: optional argument, when True, the property will be converted\n"
4124 " into its Python representation.\n"
4125 " :type coerce: bool\n"
4126 " :return: Property value or property object.\n"
4127 " :rtype: Any | :class:`bpy.types.bpy_prop`\n");
4128static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
4129{
4130 const char *path;
4131 PyObject *coerce = Py_True;
4132 PointerRNA r_ptr;
4133 PropertyRNA *r_prop;
4134 int index = -1;
4135
4137
4138 if (!PyArg_ParseTuple(args,
4139 "s" /* `path` */
4140 "|" /* Optional arguments. */
4141 "O!" /* `coerce` */
4142 ":path_resolve",
4143 &path,
4144 &PyBool_Type,
4145 &coerce))
4146 {
4147 return nullptr;
4148 }
4149
4150 if (RNA_path_resolve_full_maybe_null(&self->ptr.value(), path, &r_ptr, &r_prop, &index)) {
4151 if (r_prop) {
4152 if (index != -1) {
4153 if (index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
4154 PyErr_Format(PyExc_IndexError,
4155 "%.200s.path_resolve(\"%.200s\") index out of range",
4156 RNA_struct_identifier(self->ptr->type),
4157 path);
4158 return nullptr;
4159 }
4160
4161 return pyrna_array_index(&r_ptr, r_prop, index);
4162 }
4163
4164 if (coerce == Py_False) {
4165 return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
4166 }
4167
4168 return pyrna_prop_to_py(&r_ptr, r_prop);
4169 }
4170
4171 return pyrna_struct_CreatePyObject(&r_ptr);
4172 }
4173
4174 PyErr_Format(PyExc_ValueError,
4175 "%.200s.path_resolve(\"%.200s\") could not be resolved",
4176 RNA_struct_identifier(self->ptr->type),
4177 path);
4178 return nullptr;
4179}
4180
4182 /* Wrap. */
4183 pyrna_struct_path_from_module_doc,
4184 ".. method:: path_from_module(property=\"\", index=-1, /)\n"
4185 "\n"
4186 " Returns the full data path to this struct (as a string) from the bpy module.\n"
4187 "\n"
4188 " :param property: Optional property name to get the full path from\n"
4189 " :type property: str\n"
4190 " :param index: Optional index of the property.\n"
4191 " \"-1\" means that the property has no indices.\n"
4192 " :type index: int\n"
4193 " :return: The full path to the data.\n"
4194 " :rtype: str\n"
4195 "\n"
4196 " :raises ValueError:\n"
4197 " if the input data cannot be converted into a full data path.\n"
4198 "\n"
4199 " .. note:: Even if all input data is correct, this function might\n"
4200 " error out because Blender cannot derive a valid path.\n"
4201 " The incomplete path will be printed in the error message.\n");
4202static PyObject *pyrna_struct_path_from_module(BPy_StructRNA *self, PyObject *args)
4203{
4204 const char *error_prefix = "path_from_module(...)";
4205 const char *name = nullptr;
4206 PropertyRNA *prop;
4207 int index = -1;
4208
4210
4211 if (!PyArg_ParseTuple(args,
4212 "|" /* Optional arguments. */
4213 "s" /* `property` */
4214 "i" /* `index` */
4215 ":path_from_module",
4216 &name,
4217 &index))
4218 {
4219 return nullptr;
4220 }
4221 if (index < -1) {
4222 PyErr_Format(PyExc_ValueError, "%s: indices below -1 are not supported", error_prefix);
4223 return nullptr;
4224 }
4225
4226 std::optional<std::string> path;
4227 if (name) {
4228 prop = RNA_struct_find_property(&self->ptr.value(), name);
4229 if (prop == nullptr) {
4230 PyErr_Format(PyExc_AttributeError,
4231 "%.200s.path_from_module(\"%.200s\") not found",
4232 RNA_struct_identifier(self->ptr->type),
4233 name);
4234 return nullptr;
4235 }
4236 path = RNA_path_full_property_py_ex(&self->ptr.value(), prop, index, true);
4237 }
4238 else {
4239 if (RNA_struct_is_ID(self->ptr->type)) {
4240 path = RNA_path_full_ID_py(self->ptr->owner_id);
4241 }
4242 else {
4243 path = RNA_path_full_struct_py(&self->ptr.value());
4244 }
4245 }
4246
4247 if (!path) {
4248 if (name) {
4249 PyErr_Format(PyExc_ValueError,
4250 "%.200s.path_from_module(\"%s\", %d) found, but does not support path creation",
4251 RNA_struct_identifier(self->ptr->type),
4252 name,
4253 index);
4254 }
4255 else {
4256 PyErr_Format(PyExc_ValueError,
4257 "%.200s.path_from_module() does not support path creation for this type",
4258 RNA_struct_identifier(self->ptr->type));
4259 }
4260 return nullptr;
4261 }
4262
4263 if (path.value().back() == '.') {
4264 PyErr_Format(PyExc_ValueError,
4265 "%.200s.path_from_module() could not derive a complete path for this type.\n"
4266 "Only got \"%.200s\" as an incomplete path",
4267 RNA_struct_identifier(self->ptr->type),
4268 path.value().c_str());
4269 return nullptr;
4270 }
4271
4272 return PyC_UnicodeFromStdStr(path.value());
4273}
4274
4276 /* Wrap. */
4277 pyrna_prop_path_from_module_doc,
4278 ".. method:: path_from_module()\n"
4279 "\n"
4280 " Returns the full data path to this struct (as a string) from the bpy module.\n"
4281 "\n"
4282 " :return: The full path to the data.\n"
4283 " :rtype: str\n"
4284 "\n"
4285 " :raises ValueError:\n"
4286 " if the input data cannot be converted into a full data path.\n"
4287 "\n"
4288 " .. note:: Even if all input data is correct, this function might\n"
4289 " error out because Blender cannot derive a valid path.\n"
4290 " The incomplete path will be printed in the error message.\n");
4292{
4293 PropertyRNA *prop = self->prop;
4294
4295 const std::optional<std::string> path = RNA_path_full_property_py_ex(
4296 &self->ptr.value(), prop, -1, true);
4297
4298 if (!path) {
4299 PyErr_Format(PyExc_ValueError,
4300 "%.200s.%.200s.path_from_module() does not support path creation for this type",
4301 RNA_struct_identifier(self->ptr->type),
4303 return nullptr;
4304 }
4305
4306 if (path.value().back() == '.') {
4307 PyErr_Format(
4308 PyExc_ValueError,
4309 "%.200s.%.200s.path_from_module() could not derive a complete path for this type.\n"
4310 "Only got \"%.200s\" as an incomplete path",
4311 RNA_struct_identifier(self->ptr->type),
4313 path.value().c_str());
4314 return nullptr;
4315 }
4316
4317 return PyC_UnicodeFromStdStr(path.value());
4318}
4319
4321 /* Wrap. */
4322 pyrna_struct_path_from_id_doc,
4323 ".. method:: path_from_id(property=\"\", /)\n"
4324 "\n"
4325 " Returns the data path from the ID to this object (string).\n"
4326 "\n"
4327 " :param property: Optional property name which can be used if the path is\n"
4328 " to a property of this object.\n"
4329 " :type property: str\n"
4330 " :return: The path from :class:`bpy.types.bpy_struct.id_data`\n"
4331 " to this struct and property (when given).\n"
4332 " :rtype: str\n");
4333static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
4334{
4335 const char *name = nullptr;
4336 PropertyRNA *prop;
4337
4339
4340 if (!PyArg_ParseTuple(args,
4341 "|" /* Optional arguments. */
4342 "s" /* `property` */
4343 ":path_from_id",
4344 &name))
4345 {
4346 return nullptr;
4347 }
4348
4349 std::optional<std::string> path;
4350 if (name) {
4351 prop = RNA_struct_find_property(&self->ptr.value(), name);
4352 if (prop == nullptr) {
4353 PyErr_Format(PyExc_AttributeError,
4354 "%.200s.path_from_id(\"%.200s\") not found",
4355 RNA_struct_identifier(self->ptr->type),
4356 name);
4357 return nullptr;
4358 }
4359
4360 path = RNA_path_from_ID_to_property(&self->ptr.value(), prop);
4361 }
4362 else {
4363 path = RNA_path_from_ID_to_struct(&self->ptr.value());
4364 }
4365
4366 if (!path) {
4367 if (name) {
4368 PyErr_Format(PyExc_ValueError,
4369 "%.200s.path_from_id(\"%s\") found, but does not support path creation",
4370 RNA_struct_identifier(self->ptr->type),
4371 name);
4372 }
4373 else {
4374 PyErr_Format(PyExc_ValueError,
4375 "%.200s.path_from_id() does not support path creation for this type",
4376 RNA_struct_identifier(self->ptr->type));
4377 }
4378 return nullptr;
4379 }
4380
4381 return PyC_UnicodeFromStdStr(path.value());
4382}
4383
4385 /* Wrap. */
4386 pyrna_prop_path_from_id_doc,
4387 ".. method:: path_from_id()\n"
4388 "\n"
4389 " Returns the data path from the ID to this property (string).\n"
4390 "\n"
4391 " :return: The path from :class:`bpy.types.bpy_struct.id_data` to this property.\n"
4392 " :rtype: str\n");
4394{
4395 PropertyRNA *prop = self->prop;
4396
4397 const std::optional<std::string> path = RNA_path_from_ID_to_property(&self->ptr.value(),
4398 self->prop);
4399
4400 if (!path) {
4401 PyErr_Format(PyExc_ValueError,
4402 "%.200s.%.200s.path_from_id() does not support path creation for this type",
4403 RNA_struct_identifier(self->ptr->type),
4405 return nullptr;
4406 }
4407
4408 return PyC_UnicodeFromStdStr(path.value());
4409}
4410
4412 /* Wrap. */
4413 pyrna_prop_as_bytes_doc,
4414 ".. method:: as_bytes()\n"
4415 "\n"
4416 " Returns this string property as a byte rather than a Python string.\n"
4417 "\n"
4418 " :return: The string as bytes.\n"
4419 " :rtype: bytes\n");
4421{
4422
4423 if (RNA_property_type(self->prop) != PROP_STRING) {
4424 PyErr_Format(PyExc_TypeError,
4425 "%.200s.%.200s.as_bytes() must be a string",
4426 RNA_struct_identifier(self->ptr->type),
4428 return nullptr;
4429 }
4430
4431 PyObject *ret;
4432 char buf_fixed[256], *buf;
4433 int buf_len;
4434
4436 &self->ptr.value(), self->prop, buf_fixed, sizeof(buf_fixed), &buf_len);
4437
4438 ret = PyBytes_FromStringAndSize(buf, buf_len);
4439
4440 if (buf_fixed != buf) {
4441 MEM_delete(buf);
4442 }
4443
4444 return ret;
4445}
4446
4448 /* Wrap. */
4449 pyrna_prop_update_doc,
4450 ".. method:: update()\n"
4451 "\n"
4452 " Execute the properties update callback.\n"
4453 "\n"
4454 " .. note::\n"
4455 " This is called when assigning a property,\n"
4456 " however in rare cases it's useful to call explicitly.\n");
4457static PyObject *pyrna_prop_update(BPy_PropertyRNA *self)
4458{
4459 RNA_property_update(BPY_context_get(), &self->ptr.value(), self->prop);
4460 Py_RETURN_NONE;
4461}
4462
4464 /* Wrap. */
4465 pyrna_struct_type_recast_doc,
4466 ".. method:: type_recast()\n"
4467 "\n"
4468 " Return a new instance, this is needed because types\n"
4469 " such as textures can be changed at runtime.\n"
4470 "\n"
4471 " :return: a new instance of this object with the type initialized again.\n"
4472 " :rtype: :class:`bpy.types.bpy_struct`\n");
4474{
4475
4477
4478 PointerRNA r_ptr = RNA_pointer_recast(&self->ptr.value());
4479 return pyrna_struct_CreatePyObject(&r_ptr);
4480}
4481
4485static PyObject *pyrna_struct_bl_rna_find_subclass_recursive(PyObject *cls, const char *id)
4486{
4487 PyObject *ret_test = nullptr;
4488 PyObject *subclasses = static_cast<PyObject *>(
4489 (reinterpret_cast<PyTypeObject *>(cls))->tp_subclasses);
4490 if (subclasses) {
4491 /* Unfortunately we can't use the dict key because Python class names
4492 * don't match the bl_idname used internally. */
4493 BLI_assert(PyDict_CheckExact(subclasses));
4494 PyObject *key = nullptr;
4495 Py_ssize_t pos = 0;
4496 PyObject *value = nullptr;
4497 while (PyDict_Next(subclasses, &pos, &key, &value)) {
4498 BLI_assert(PyWeakref_CheckRef(value));
4499 PyObject *value_ref = pyweakref_get_ref(value);
4500 if (!value_ref) {
4501 continue;
4502 }
4503
4504 BPy_StructRNA *py_srna = reinterpret_cast<BPy_StructRNA *>(PyDict_GetItem(
4505 (reinterpret_cast<PyTypeObject *>(value_ref))->tp_dict, bpy_intern_str_bl_rna));
4506 if (py_srna) {
4507 StructRNA *srna = static_cast<StructRNA *>(py_srna->ptr->data);
4508 if (STREQ(id, RNA_struct_identifier(srna))) {
4509 ret_test = value_ref;
4510 }
4511 }
4512 if (!ret_test) {
4513 ret_test = pyrna_struct_bl_rna_find_subclass_recursive(value_ref, id);
4514 }
4515 /* NOTE: `ret_test` is now a borrowed reference,
4516 * Acceptable since the type is kept alive by its instances and defining module. */
4517 Py_DECREF(value_ref);
4518
4519 if (ret_test) {
4520 break;
4521 }
4522 }
4523 }
4524 return ret_test;
4525}
4526
4528 /* Wrap. */
4529 pyrna_struct_bl_rna_get_subclass_py_doc,
4530 ".. classmethod:: bl_rna_get_subclass_py(id, default=None, /)\n"
4531 "\n"
4532 " :param id: The RNA type identifier.\n"
4533 " :type id: str\n"
4534 " :param default: The value to return when not found.\n"
4535 " :type default: type | None\n"
4536 " :return: The class or default when not found.\n"
4537 " :rtype: type\n");
4538static PyObject *pyrna_struct_bl_rna_get_subclass_py(PyObject *cls, PyObject *args)
4539{
4540 char *id;
4541 PyObject *ret_default = Py_None;
4542
4543 if (!PyArg_ParseTuple(args,
4544 "s" /* `id` */
4545 "|" /* Optional arguments. */
4546 "O" /* `default` */
4547 ":bl_rna_get_subclass_py",
4548 &id,
4549 &ret_default))
4550 {
4551 return nullptr;
4552 }
4554 if (ret == nullptr) {
4555 ret = ret_default;
4556 }
4557 return Py_NewRef(ret);
4558}
4559
4561 /* Wrap. */
4562 pyrna_struct_bl_rna_get_subclass_doc,
4563 ".. classmethod:: bl_rna_get_subclass(id, default=None, /)\n"
4564 "\n"
4565 " :param id: The RNA type identifier.\n"
4566 " :type id: str\n"
4567 " :param default: The value to return when not found.\n"
4568 " :type default: :class:`bpy.types.Struct` | None\n"
4569 " :return: The RNA type or default when not found.\n"
4570 " :rtype: :class:`bpy.types.Struct`\n");
4571static PyObject *pyrna_struct_bl_rna_get_subclass(PyObject *cls, PyObject *args)
4572{
4573 const char *id;
4574 PyObject *ret_default = Py_None;
4575
4576 if (!PyArg_ParseTuple(args,
4577 "s" /* `id` */
4578 "|" /* Optional arguments. */
4579 "O" /* `default` */
4580 ":bl_rna_get_subclass",
4581 &id,
4582 &ret_default))
4583 {
4584 return nullptr;
4585 }
4586
4587 const BPy_StructRNA *py_srna = reinterpret_cast<BPy_StructRNA *>(
4588 PyDict_GetItem((reinterpret_cast<PyTypeObject *>(cls))->tp_dict, bpy_intern_str_bl_rna));
4589 if (py_srna == nullptr) {
4590 PyErr_SetString(PyExc_ValueError, "Not a registered class");
4591 return nullptr;
4592 }
4593 const StructRNA *srna_base = static_cast<const StructRNA *>(py_srna->ptr->data);
4594
4595 if (srna_base == RNA_Node) {
4596 /* If the given idname is an alias, translate it to the proper idname. */
4597 const UString idname = bke::node_type_find_alias(UString(id));
4598
4599 bke::bNodeType *nt = bke::node_type_find(idname);
4600 if (nt) {
4601 PointerRNA ptr = RNA_pointer_create_discrete(nullptr, RNA_Struct, nt->rna_ext.srna);
4602 return pyrna_struct_CreatePyObject(&ptr);
4603 }
4604 }
4605 else {
4606 /* TODO: panels, menus etc. */
4607 PyErr_Format(
4608 PyExc_ValueError, "Class type \"%.200s\" not supported", RNA_struct_identifier(srna_base));
4609 return nullptr;
4610 }
4611
4612 return Py_NewRef(ret_default);
4613}
4614
4616 /* Wrap. */
4617 pyrna_struct_get_ancestors_doc,
4618 ".. method:: rna_ancestors()\n"
4619 "\n"
4620 " Return the chain of data containing this struct, if known.\n"
4621 " The first item is the root (typically an ID), the last one is the immediate parent.\n"
4622 " May be empty.\n"
4623 "\n"
4624 " :return: a list of this object's ancestors.\n"
4625 " :rtype: list[:class:`bpy.types.bpy_struct`]\n");
4627{
4629
4630 PyObject *ret;
4631 const int ancestors_num(self->ptr->ancestors.size());
4632
4633 ret = PyList_New(ancestors_num);
4634
4635 for (int i = 0; i < ancestors_num; i++) {
4636 PointerRNA ancestor_ptr = RNA_pointer_create_from_ancestor(self->ptr.value(), i);
4637 PyObject *ancestor = pyrna_struct_CreatePyObject(&ancestor_ptr);
4638 PyList_SET_ITEM(ret, i, ancestor);
4639 }
4640
4641 return ret;
4642}
4643
4644static void pyrna_dir_members_py__add_keys(PyObject *list, PyObject *dict)
4645{
4646 PyObject *list_tmp;
4647
4648 list_tmp = PyDict_Keys(dict);
4649 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
4650 Py_DECREF(list_tmp);
4651}
4652
4653static void pyrna_dir_members_py(PyObject *list, PyObject *self)
4654{
4655 PyObject *dict;
4656 PyObject **dict_ptr;
4657
4658 dict_ptr = _PyObject_GetDictPtr(self);
4659
4660 if (dict_ptr && (dict = *dict_ptr)) {
4662 }
4663
4664 dict = (static_cast<PyTypeObject *>(Py_TYPE(self)))->tp_dict;
4665 if (dict) {
4667 }
4668
4669 /* Since this is least common case, handle it last. */
4670 if (BPy_PropertyRNA_Check(self)) {
4671 BPy_PropertyRNA *self_prop = reinterpret_cast<BPy_PropertyRNA *>(self);
4672 if (RNA_property_type(self_prop->prop) == PROP_COLLECTION) {
4673 if (std::optional<PointerRNA> c_ptr = RNA_property_collection_type_get(
4674 &self_prop->ptr.value(), self_prop->prop))
4675 {
4676 PyObject *cls = pyrna_struct_Subtype(&c_ptr.value()); /* borrows */
4677 dict = (reinterpret_cast<PyTypeObject *>(cls))->tp_dict;
4679 Py_DECREF(cls);
4680 }
4681 }
4682 }
4683}
4684
4685static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
4686{
4687 const char *idname;
4688
4689 /* For looping over attributes and functions. */
4690 PropertyRNA *iterprop;
4691
4692 {
4693 PointerRNA tptr = RNA_pointer_create_discrete(nullptr, RNA_Struct, ptr->type);
4694 iterprop = RNA_struct_find_property(&tptr, "functions");
4695
4696 RNA_PROP_BEGIN (&tptr, itemptr, iterprop) {
4697 FunctionRNA *func = static_cast<FunctionRNA *>(itemptr.data);
4698 if (RNA_function_defined(func)) {
4699 idname = RNA_function_identifier(static_cast<FunctionRNA *>(itemptr.data));
4700 PyList_APPEND(list, PyUnicode_FromString(idname));
4701 }
4702 }
4704 }
4705
4706 {
4707 /*
4708 * Collect RNA attributes
4709 */
4710 iterprop = RNA_struct_iterator_property(ptr->type);
4711
4712 BPy_NamePropAsPyObject_Cache nameprop_cache = {nullptr};
4713 RNA_PROP_BEGIN (ptr, itemptr, iterprop) {
4714 /* Custom-properties are exposed using `__getitem__`, exclude from `__dir__`. */
4715 if (RNA_property_is_idprop(static_cast<const PropertyRNA *>(itemptr.data))) {
4716 continue;
4717 }
4718 if (PyObject *name_py = pyrna_struct_get_nameprop_as_pyobject(&itemptr, nameprop_cache)) {
4719 PyList_APPEND(list, name_py);
4720 }
4721 }
4723 }
4724}
4725
4726static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
4727{
4728 PyObject *ret;
4729
4731
4732 /* Include this in case this instance is a subtype of a Python class
4733 * In these instances we may want to return a function or variable provided by the subtype. */
4734 ret = PyList_New(0);
4735
4736 if (!BPy_StructRNA_CheckExact(self)) {
4737 pyrna_dir_members_py(ret, reinterpret_cast<PyObject *>(self));
4738 }
4739
4740 pyrna_dir_members_rna(ret, &self->ptr.value());
4741
4742 if (self->ptr->type == RNA_Context) {
4743 ListBaseT<LinkData> lb = CTX_data_dir_get(static_cast<const bContext *>(self->ptr->data));
4744
4745 for (LinkData &link : lb) {
4746 PyList_APPEND(ret, PyUnicode_FromString(static_cast<const char *>(link.data)));
4747 }
4748
4749 lb.free_no_destruct();
4750 }
4751
4752 {
4753 /* set(), this is needed to remove-doubles because the deferred
4754 * register-props will be in both the Python __dict__ and accessed as RNA */
4755
4756 PyObject *set = PySet_New(ret);
4757
4758 Py_DECREF(ret);
4759 ret = PySequence_List(set);
4760 Py_DECREF(set);
4761 }
4762
4763 return ret;
4764}
4765
4767 /* Wrap. */
4768 pyrna_struct_id_properties_ensure_doc,
4769 ".. method:: id_properties_ensure()\n"
4770 "\n"
4771 " :return: the parent group for an RNA struct's custom IDProperties.\n"
4772 " :rtype: :class:`idprop.types.IDPropertyGroup`\n");
4774{
4776
4777 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
4778 PyErr_SetString(PyExc_TypeError, "This type doesn't support IDProperties");
4779 return nullptr;
4780 }
4781
4782 IDProperty *idprops = RNA_struct_idprops(&self->ptr.value(), true);
4783
4784 /* This is a paranoid check that theoretically might not be necessary.
4785 * It allows the possibility that some structs can't ensure IDProperties. */
4786 if (idprops == nullptr) {
4787 Py_RETURN_NONE;
4788 }
4789
4790 BPy_IDProperty *group = PyObject_New(BPy_IDProperty, &BPy_IDGroup_Type);
4791 group->owner_id = self->ptr->owner_id;
4792 group->prop = idprops;
4793 group->parent = nullptr;
4794 return reinterpret_cast<PyObject *>(group);
4795}
4796
4798 /* Wrap. */
4799 pyrna_struct_id_properties_ui_doc,
4800 ".. method:: id_properties_ui(key, /)\n"
4801 "\n"
4802 " :param key: String name of the property.\n"
4803 " :type key: str\n"
4804 " :return: An object used to manage an IDProperty's UI data.\n"
4805 " :rtype: :class:`idprop.types.IDPropertyUIManager` | None\n");
4806static PyObject *pyrna_struct_id_properties_ui(BPy_StructRNA *self, PyObject *args)
4807{
4809
4810 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
4811 PyErr_SetString(PyExc_TypeError, "This type doesn't support IDProperties");
4812 return nullptr;
4813 }
4814
4815 const char *key;
4816 if (!PyArg_ParseTuple(args,
4817 "s" /* `key` */
4818 ":id_properties_ui",
4819 &key))
4820 {
4821 return nullptr;
4822 }
4823
4824 IDProperty *parent_group = RNA_struct_idprops(&self->ptr.value(), true);
4825
4826 /* This is a paranoid check that theoretically might not be necessary.
4827 * It allows the possibility that some structs can't ensure IDProperties. */
4828 if (parent_group == nullptr) {
4829 Py_RETURN_NONE;
4830 }
4831
4832 IDProperty *property = IDP_GetPropertyFromGroup(parent_group, key);
4833 if (property == nullptr) {
4834 PyErr_SetString(PyExc_KeyError, "Property not found in IDProperty group");
4835 return nullptr;
4836 }
4837
4838 if (!IDP_ui_data_supported(property)) {
4839 PyErr_Format(PyExc_TypeError, "IDProperty \"%s\" does not support UI data", property->name);
4840 return nullptr;
4841 }
4842
4843 BPy_IDPropertyUIManager *ui_manager = PyObject_New(BPy_IDPropertyUIManager,
4845 ui_manager->property = property;
4846 return reinterpret_cast<PyObject *>(ui_manager);
4847}
4848
4850 /* Wrap. */
4851 pyrna_struct_id_properties_clear_doc,
4852 ".. method:: id_properties_clear()\n"
4853 "\n"
4854 " Remove the parent group for an RNA struct's custom IDProperties.\n");
4856{
4858
4859 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
4860 PyErr_SetString(PyExc_TypeError, "This type doesn't support IDProperties");
4861 return nullptr;
4862 }
4863
4864 IDProperty **idprops = RNA_struct_idprops_p(&self->ptr.value());
4865
4866 if (*idprops) {
4867 IDP_FreeProperty(*idprops);
4868 *idprops = nullptr;
4869 }
4870
4871 Py_RETURN_NONE;
4872}
4873
4874/* ---------------getattr-------------------------------------------- */
4875static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
4876{
4877 const char *name = PyUnicode_AsUTF8(pyname);
4878 PyObject *ret;
4879 PropertyRNA *prop;
4880 FunctionRNA *func;
4881
4882 /* Allow `__class__` so `isinstance(ob, cls)` can be used without raising an exception. */
4883 PYRNA_STRUCT_CHECK_OBJ_UNLESS(self, name && STREQ(name, "__class__"));
4884
4885 if (name == nullptr) {
4886 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
4887 ret = nullptr;
4888 }
4889 else if (
4890 /* RNA can't start with a "_", so for __dict__ and similar we can skip using RNA lookups. */
4891 name[0] == '_')
4892 {
4893 /* Annoying exception, maybe we need to have different types for this... */
4894 if (STR_ELEM(name, "__getitem__", "__setitem__") && !RNA_struct_idprops_check(self->ptr->type))
4895 {
4896 PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
4897 ret = nullptr;
4898 }
4899 else {
4900 ret = PyObject_GenericGetAttr(reinterpret_cast<PyObject *>(self), pyname);
4901 }
4902 }
4903 else if ((prop = RNA_struct_find_property(&self->ptr.value(), name))) {
4904 ret = pyrna_prop_to_py(&self->ptr.value(), prop);
4905 }
4906 /* RNA function only if callback is declared (no optional functions). */
4907 else if ((func = RNA_struct_find_function(self->ptr->type, name)) && RNA_function_defined(func))
4908 {
4909 ret = pyrna_func_CreatePyObject(&self->ptr.value(), func);
4910 }
4911 else if (self->ptr->type == RNA_Context) {
4912 bContext *C = static_cast<bContext *>(self->ptr->data);
4913 if (C == nullptr) {
4914 PyErr_Format(PyExc_AttributeError,
4915 "bpy_struct: Context is 'null', cannot get \"%.200s\" from context",
4916 name);
4917 ret = nullptr;
4918 }
4919 else {
4920 PointerRNA newptr;
4921 Vector<PointerRNA> newlb;
4922 PropertyRNA *newprop;
4923 int newindex;
4924 StringRef newstr;
4925 std::optional<int64_t> newint;
4926 ContextDataType newtype;
4927
4928 /* An empty string is used to implement #CTX_data_dir_get,
4929 * without this check `getattr(context, "")` succeeds. */
4930 eContextResult done;
4931 if (name[0]) {
4933 C, name, &newptr, &newlb, &newprop, &newindex, &newstr, &newint, &newtype));
4934 }
4935 else {
4936 /* Fall through to built-in `getattr`. */
4938 }
4939
4940 if (done == CTX_RESULT_OK) {
4941 switch (newtype) {
4943 if (!newptr) {
4944 ret = Py_None;
4945 Py_INCREF(ret);
4946 }
4947 else {
4949 }
4950 break;
4952 if (newstr.is_empty()) {
4953 ret = Py_None;
4954 Py_INCREF(ret);
4955 }
4956 else {
4957 ret = PyUnicode_FromStringAndSize(newstr.data(), newstr.size());
4958 }
4959 break;
4960 }
4962 if (!newint.has_value()) {
4963 ret = Py_None;
4964 Py_INCREF(ret);
4965 }
4966 else {
4967 ret = PyLong_FromLong(*newint);
4968 }
4969 break;
4970 }
4972 ret = PyList_New(0);
4973 for (PointerRNA &ptr : newlb) {
4974 PyList_APPEND(ret, pyrna_struct_CreatePyObject(&ptr));
4975 }
4976 break;
4977 }
4979 if (newprop != nullptr) {
4980 /* Create pointer to parent ID, and path from ID to property. */
4981 PointerRNA idptr;
4982
4983 PointerRNA *base_ptr;
4984 std::optional<std::string> path_str;
4985
4986 if (newptr.owner_id) {
4987 path_str = RNA_path_from_ID_to_property(&newptr, newprop);
4988 idptr = RNA_id_pointer_create(newptr.owner_id);
4989 base_ptr = &idptr;
4990 }
4991 else {
4992 path_str = RNA_path_from_ptr_to_property_index(&newptr, newprop, 0, -1);
4993 base_ptr = &newptr;
4994 }
4995
4996 if (path_str) {
4997 ret = PyTuple_New(3);
5000 PyC_UnicodeFromStdStr(path_str.value()),
5001 PyLong_FromLong(newindex));
5002 }
5003 else {
5004 ret = Py_None;
5005 Py_INCREF(ret);
5006 }
5007 }
5008 else {
5009 ret = Py_None;
5010 Py_INCREF(ret);
5011 }
5012 break;
5013 }
5014 default:
5015 /* Should never happen. */
5016 BLI_assert_msg(0, "Invalid context type");
5017
5018 PyErr_Format(PyExc_AttributeError,
5019 "bpy_struct: Context type invalid %d, cannot get \"%.200s\" from context",
5020 newtype,
5021 name);
5022 ret = nullptr;
5023 break;
5024 }
5025 }
5026 else if (done == CTX_RESULT_NO_DATA) {
5027 ret = Py_None;
5028 Py_INCREF(ret);
5029 }
5030 else { /* Not found in the context. */
5031 /* Lookup the subclass. raise an error if it's not found. */
5032 ret = PyObject_GenericGetAttr(reinterpret_cast<PyObject *>(self), pyname);
5033 }
5034 }
5035 }
5036 else {
5037#if 0
5038 PyErr_Format(PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" not found", name);
5039 ret = nullptr;
5040#endif
5041 /* Include this in case this instance is a subtype of a Python class
5042 * In these instances we may want to return a function or variable provided by the subtype
5043 *
5044 * Also needed to return methods when it's not a subtype.
5045 */
5046
5047 /* The error raised here will be displayed */
5048 ret = PyObject_GenericGetAttr(reinterpret_cast<PyObject *>(self), pyname);
5049 }
5050
5051 return ret;
5052}
5053
5054#if 0
5055static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
5056{
5057 PyObject *dict = *(_PyObject_GetDictPtr((PyObject *)self));
5058 if (dict == nullptr) [[unlikely]] {
5059 return 0;
5060 }
5061
5062 return PyDict_Contains(dict, pyname);
5063}
5064#endif
5065
5066/* --------------- setattr------------------------------------------- */
5067
5068#if 0
5069static PyObject *pyrna_struct_meta_idprop_getattro(PyObject *cls, PyObject *attr)
5070{
5071 PyObject *ret = PyType_Type.tp_getattro(cls, attr);
5072
5073/* Allows:
5074 * >>> bpy.types.Scene.foo = BoolProperty()
5075 * >>> bpy.types.Scene.foo
5076 * <bpy_struct, BoolProperty("foo")>
5077 * ...rather than returning the deferred class register tuple
5078 * as checked by BPy_PropDeferred_CheckTypeExact()
5079 *
5080 * Disable for now,
5081 * this is faking internal behavior in a way that's too tricky to maintain well. */
5082# if 0
5083 if ((ret == nullptr) /* || BPy_PropDeferred_CheckTypeExact(ret) */) {
5084 PyErr_Clear(); /* Clear error from tp_getattro. */
5085 StructRNA *srna = srna_from_self(cls, "StructRNA.__getattr__");
5086 if (srna) {
5087 PropertyRNA *prop = RNA_struct_type_find_property_no_base(srna, UString(PyUnicode_AsUTF8(attr)));
5088 if (prop) {
5089 PointerRNA tptr = RNA_pointer_create_discrete(nullptr, RNA_Property, prop);
5091 }
5092 }
5093 if (ret == nullptr) {
5094 PyErr_Format(PyExc_AttributeError,
5095 "StructRNA.__getattr__: attribute \"%.200s\" not found",
5096 PyUnicode_AsUTF8(attr));
5097 }
5098 }
5099# endif
5100
5101 return ret;
5102}
5103#endif
5104
5105static int pyrna_struct_meta_idprop_setattro(PyObject *cls, PyObject *attr, PyObject *value)
5106{
5107 StructRNA *srna = srna_from_self(cls, "StructRNA.__setattr__");
5108 const bool is_deferred_prop = (value && BPy_PropDeferred_CheckTypeExact(value));
5109 const char *attr_str = PyUnicode_AsUTF8(attr);
5110
5111 if (srna && !pyrna_write_check() &&
5112 (is_deferred_prop || RNA_struct_type_find_property_no_base(srna, UString(attr_str))))
5113 {
5114 PyErr_Format(PyExc_AttributeError,
5115 "pyrna_struct_meta_idprop_setattro() "
5116 "cannot set in readonly state '%.200s.%S'",
5117 (reinterpret_cast<PyTypeObject *>(cls))->tp_name,
5118 attr);
5119 return -1;
5120 }
5121
5122 if (srna == nullptr) {
5123/* Allow setting on unregistered classes which can be registered later on. */
5124#if 0
5125 if (value && is_deferred_prop) {
5126 PyErr_Format(PyExc_AttributeError,
5127 "pyrna_struct_meta_idprop_setattro() unable to get srna from class '%.200s'",
5128 ((PyTypeObject *)cls)->tp_name);
5129 return -1;
5130 }
5131#endif
5132 /* srna_from_self may set an error. */
5133 PyErr_Clear();
5134 return PyType_Type.tp_setattro(cls, attr, value);
5135 }
5136
5137 if (value) {
5138 /* Check if the value is a property. */
5139 if (is_deferred_prop) {
5140 const int ret = deferred_register_prop(srna, attr, value);
5141 if (ret == -1) {
5142 /* Error set. */
5143 return ret;
5144 }
5145
5146 /* pass through and assign to the classes __dict__ as well
5147 * so when the value isn't assigned it still creates the RNA property,
5148 * but gets confusing from script writers POV if the assigned value can't be read back. */
5149 }
5150 else {
5151 /* Remove existing property if it's set or we also end up with confusion. */
5152 RNA_def_property_free_identifier(srna, attr_str); /* Ignore on failure. */
5153 }
5154 }
5155 else { /* __delattr__ */
5156 /* First find if this is a registered property. */
5157 const int ret = RNA_def_property_free_identifier(srna, attr_str);
5158 if (ret == -1) {
5159 PyErr_Format(
5160 PyExc_TypeError, "struct_meta_idprop.detattr(): '%s' not a dynamic property", attr_str);
5161 return -1;
5162 }
5163 }
5164
5165 /* Fall back to standard Python's `delattr/setattr`. */
5166 return PyType_Type.tp_setattro(cls, attr, value);
5167}
5168
5169static int pyrna_struct_setattro(BPy_StructRNA *self, PyObject *pyname, PyObject *value)
5170{
5171 const char *name = PyUnicode_AsUTF8(pyname);
5172 PropertyRNA *prop = nullptr;
5173 FunctionRNA *func = nullptr;
5174
5176
5177#ifdef USE_PEDANTIC_WRITE
5178 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), pyname)) {
5179 return -1;
5180 }
5181#endif /* USE_PEDANTIC_WRITE */
5182
5183 if (name == nullptr) {
5184 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __setattr__ must be a string");
5185 return -1;
5186 }
5187 if (name[0] != '_' && (prop = RNA_struct_find_property(&self->ptr.value(), name))) {
5188 if (!RNA_property_editable_flag(&self->ptr.value(), prop)) {
5189 PyErr_Format(PyExc_AttributeError,
5190 "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only",
5192 RNA_struct_identifier(self->ptr->type));
5193 return -1;
5194 }
5195 }
5196 else if (name[0] != '_' && (func = RNA_struct_find_function(self->ptr->type, name)) &&
5198 {
5199 /* Python differentiates between non-existent and read-only for values in __dict__ which covers
5200 * PyMethodDef and PyGetSetDef. This is only needed because RNA functions are not part of the
5201 * __dict__. */
5202 PyErr_Format(PyExc_AttributeError,
5203 "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only",
5205 RNA_struct_identifier(self->ptr->type));
5206 return -1;
5207 }
5208 else if (self->ptr->type == RNA_Context) {
5209 /* Code just raises correct error, context prop's can't be set,
5210 * unless it's a part of the py class. */
5211 bContext *C = static_cast<bContext *>(self->ptr->data);
5212 if (C == nullptr) {
5213 PyErr_Format(PyExc_AttributeError,
5214 "bpy_struct: Context is 'null', cannot set \"%.200s\" from context",
5215 name);
5216 return -1;
5217 }
5218
5219 PointerRNA newptr;
5220 Vector<PointerRNA> newlb;
5221 PropertyRNA *newprop;
5222 int newindex;
5223 StringRef newstr;
5224 std::optional<int64_t> newint;
5225 ContextDataType newtype;
5226
5227 const eContextResult done = eContextResult(
5228 CTX_data_get(C, name, &newptr, &newlb, &newprop, &newindex, &newstr, &newint, &newtype));
5229
5230 if (done == CTX_RESULT_OK) {
5231 PyErr_Format(
5232 PyExc_AttributeError, "bpy_struct: Context property \"%.200s\" is read-only", name);
5233 return -1;
5234 }
5235 }
5236
5237 /* pyrna_py_to_prop sets its own exceptions */
5238 if (prop) {
5239 if (value == nullptr) {
5240 PyErr_SetString(PyExc_AttributeError, "bpy_struct: del not supported");
5241 return -1;
5242 }
5243 return pyrna_py_to_prop(
5244 &self->ptr.value(), prop, nullptr, value, "bpy_struct: item.attr = val:", nullptr);
5245 }
5246
5247 return PyObject_GenericSetAttr(reinterpret_cast<PyObject *>(self), pyname, value);
5248}
5249
5250static PyObject *pyrna_prop_dir(BPy_PropertyRNA *self)
5251{
5252 PyObject *ret;
5253
5254 /* Include this in case this instance is a subtype of a Python class
5255 * In these instances we may want to return a function or variable provided by the subtype. */
5256 ret = PyList_New(0);
5257
5258 if (!BPy_PropertyRNA_CheckExact(self)) {
5259 pyrna_dir_members_py(ret, reinterpret_cast<PyObject *>(self));
5260 }
5261
5262 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
5263 if (std::optional<PointerRNA> c_ptr = RNA_property_collection_type_get(&self->ptr.value(),
5264 self->prop))
5265 {
5266 pyrna_dir_members_rna(ret, &c_ptr.value());
5267 }
5268 }
5269
5270 return ret;
5271}
5272
5273static PyObject *pyrna_prop_array_getattro(BPy_PropertyRNA *self, PyObject *pyname)
5274{
5275 return PyObject_GenericGetAttr(reinterpret_cast<PyObject *>(self), pyname);
5276}
5277
5278static PyObject *pyrna_prop_collection_getattro(BPy_PropertyRNA *self, PyObject *pyname)
5279{
5280 const char *name = PyUnicode_AsUTF8(pyname);
5281
5282 if (name == nullptr) {
5283 PyErr_SetString(PyExc_AttributeError, "bpy_prop_collection: __getattr__ must be a string");
5284 return nullptr;
5285 }
5286 if (name[0] != '_') {
5287 PyObject *ret;
5288 PropertyRNA *prop;
5289 FunctionRNA *func;
5290
5291 if (std::optional<PointerRNA> c_ptr = RNA_property_collection_type_get(&self->ptr.value(),
5292 self->prop))
5293 {
5294 if ((prop = RNA_struct_find_property(&c_ptr.value(), name))) {
5295 ret = pyrna_prop_to_py(&c_ptr.value(), prop);
5296
5297 return ret;
5298 }
5299 if ((func = RNA_struct_find_function(c_ptr->type, name))) {
5300 PyObject *self_collection = pyrna_struct_CreatePyObject(&c_ptr.value());
5302 &(reinterpret_cast<BPy_DummyPointerRNA *>(self_collection))->ptr.value(), func);
5303 Py_DECREF(self_collection);
5304
5305 return ret;
5306 }
5307 }
5308 }
5309
5310#if 0
5311 return PyObject_GenericGetAttr((PyObject *)self, pyname);
5312#else
5313 {
5314 /* Could just do this except for 1 awkward case.
5315 * `PyObject_GenericGetAttr((PyObject *)self, pyname);`
5316 * so as to support `bpy.data.libraries.load()` */
5317
5318 PyObject *ret = _PyObject_GenericGetAttrWithDict(
5319 reinterpret_cast<PyObject *>(self), pyname, nullptr, 1);
5320
5321 /* Check the '_' prefix to avoid inheriting `__call__` and similar. */
5322 if ((ret == nullptr) && (name[0] != '_')) {
5323 /* Since this is least common case, handle it last. */
5324 if (std::optional<PointerRNA> c_ptr = RNA_property_collection_type_get(&self->ptr.value(),
5325 self->prop))
5326 {
5327 PyObject *cls = pyrna_struct_Subtype(&c_ptr.value());
5328 ret = _PyObject_GenericGetAttrWithDict(cls, pyname, nullptr, 1);
5329 Py_DECREF(cls);
5330
5331 if (ret != nullptr) {
5332 if (Py_TYPE(ret) == &PyMethodDescr_Type) {
5333 PyMethodDef *m = (reinterpret_cast<PyMethodDescrObject *>(ret))->d_method;
5334 /* TODO: #METH_CLASS */
5335 if (m->ml_flags & METH_STATIC) {
5336 /* Keep 'ret' as-is. */
5337 }
5338 else {
5339 Py_DECREF(ret);
5340 ret = PyCMethod_New(m, reinterpret_cast<PyObject *>(self), nullptr, nullptr);
5341 }
5342 }
5343 }
5344 }
5345 }
5346
5347 if (ret == nullptr) {
5348 PyErr_Format(
5349 PyExc_AttributeError, "bpy_prop_collection: attribute \"%.200s\" not found", name);
5350 }
5351
5352 return ret;
5353 }
5354#endif
5355}
5356
5357/* --------------- setattr------------------------------------------- */
5358static int pyrna_prop_collection_setattro(BPy_PropertyRNA *self, PyObject *pyname, PyObject *value)
5359{
5360 const char *name = PyUnicode_AsUTF8(pyname);
5361 PropertyRNA *prop;
5362
5363#ifdef USE_PEDANTIC_WRITE
5364 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), pyname)) {
5365 return -1;
5366 }
5367#endif /* USE_PEDANTIC_WRITE */
5368
5369 if (name == nullptr) {
5370 PyErr_SetString(PyExc_AttributeError, "bpy_prop: __setattr__ must be a string");
5371 return -1;
5372 }
5373 if (value == nullptr) {
5374 PyErr_SetString(PyExc_AttributeError, "bpy_prop: del not supported");
5375 return -1;
5376 }
5377 if (std::optional<PointerRNA> c_ptr = RNA_property_collection_type_get(&self->ptr.value(),
5378 self->prop))
5379 {
5380 if ((prop = RNA_struct_find_property(&c_ptr.value(), name))) {
5381 /* pyrna_py_to_prop sets its own exceptions. */
5382 return pyrna_py_to_prop(
5383 &c_ptr.value(), prop, nullptr, value, "BPy_PropertyRNA - Attribute (setattr):", nullptr);
5384 }
5385 }
5386
5387 PyErr_Format(PyExc_AttributeError, "bpy_prop_collection: attribute \"%.200s\" not found", name);
5388 return -1;
5389}
5390
5395 /* Wrap. */
5396 pyrna_prop_collection_idprop_add_doc,
5397 ".. method:: add()\n"
5398 "\n"
5399 " This is a function to add a new item to a collection.\n"
5400 "\n"
5401 " :return: A newly created item.\n"
5402 " :rtype: Any\n");
5404{
5405 PointerRNA r_ptr;
5406
5407#ifdef USE_PEDANTIC_WRITE
5408 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), nullptr)) {
5409 return nullptr;
5410 }
5411#endif /* USE_PEDANTIC_WRITE */
5412
5413 RNA_property_collection_add(&self->ptr.value(), self->prop, &r_ptr);
5414 if (!r_ptr) {
5415 PyErr_SetString(PyExc_TypeError,
5416 "bpy_prop_collection.add(): not supported for this collection");
5417 return nullptr;
5418 }
5419
5420 return pyrna_struct_CreatePyObject(&r_ptr);
5421}
5422
5424 /* Wrap. */
5425 pyrna_prop_collection_idprop_remove_doc,
5426 ".. method:: remove(index)\n"
5427 "\n"
5428 " This is a function to remove an item from a collection.\n"
5429 "\n"
5430 " :param index: Index of the item to be removed.\n"
5431 " :type index: int\n");
5432static PyObject *pyrna_prop_collection_idprop_remove(BPy_PropertyRNA *self, PyObject *value)
5433{
5434 const int key = PyLong_AsLong(value);
5435
5436#ifdef USE_PEDANTIC_WRITE
5437 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), nullptr)) {
5438 return nullptr;
5439 }
5440#endif /* USE_PEDANTIC_WRITE */
5441
5442 if (key == -1 && PyErr_Occurred()) {
5443 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove(): expected one int argument");
5444 return nullptr;
5445 }
5446
5447 if (!RNA_property_collection_remove(&self->ptr.value(), self->prop, key)) {
5448 PyErr_SetString(PyExc_TypeError,
5449 "bpy_prop_collection.remove() not supported for this collection");
5450 return nullptr;
5451 }
5452
5453 Py_RETURN_NONE;
5454}
5455
5457 /* Wrap. */
5458 pyrna_prop_collection_idprop_clear_doc,
5459 ".. method:: clear()\n"
5460 "\n"
5461 " This is a function to remove all items from a collection.\n");
5463{
5464#ifdef USE_PEDANTIC_WRITE
5465 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), nullptr)) {
5466 return nullptr;
5467 }
5468#endif /* USE_PEDANTIC_WRITE */
5469
5470 RNA_property_collection_clear(&self->ptr.value(), self->prop);
5471
5472 Py_RETURN_NONE;
5473}
5474
5476 /* Wrap. */
5477 pyrna_prop_collection_idprop_move_doc,
5478 ".. method:: move(src_index, dst_index)\n"
5479 "\n"
5480 " This is a function to move an item in a collection.\n"
5481 "\n"
5482 " :param src_index: Source item index.\n"
5483 " :type src_index: int\n"
5484 " :param dst_index: Destination item index.\n"
5485 " :type dst_index: int\n");
5486static PyObject *pyrna_prop_collection_idprop_move(BPy_PropertyRNA *self, PyObject *args)
5487{
5488 int src_index = 0, dst_index = 0;
5489
5490#ifdef USE_PEDANTIC_WRITE
5491 if (rna_disallow_writes && rna_id_write_error(&self->ptr.value(), nullptr)) {
5492 return nullptr;
5493 }
5494#endif /* USE_PEDANTIC_WRITE */
5495
5496 if (!PyArg_ParseTuple(args,
5497 "i" /* `src_index` */
5498 "i" /* `dst_index` */
5499 ":move",
5500 &src_index,
5501 &dst_index))
5502 {
5503 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move(): expected two ints as arguments");
5504 return nullptr;
5505 }
5506
5508 &self->ptr.value(), self->prop, src_index, dst_index);
5509 if (!pyrna_status_ok_or_error(status, "bpy_prop_collection.move")) {
5510 return nullptr;
5511 }
5512
5513 Py_RETURN_NONE;
5514}
5515
5517 /* Wrap. */
5518 pyrna_struct_get_id_data_doc,
5519 "The :class:`bpy.types.ID` object this data-block is from or None, "
5520 "(not available for all data types) (readonly)\n"
5521 "\n"
5522 ":type: :class:`bpy.types.ID`\n");
5523static PyObject *pyrna_struct_get_id_data(BPy_DummyPointerRNA *self, void * /*closure*/)
5524{
5525 /* Used for struct and pointer since both have a ptr. */
5526 if (self->ptr->owner_id) {
5527 PointerRNA id_ptr = RNA_id_pointer_create(id_cast<ID *>(self->ptr->owner_id));
5528 return pyrna_struct_CreatePyObject(&id_ptr);
5529 }
5530
5531 Py_RETURN_NONE;
5532}
5533
5535 /* Wrap. */
5536 pyrna_struct_get_data_doc,
5537 "The data this property is using, (readonly)\n"
5538 "\n"
5539 ":type: :class:`bpy.types.bpy_struct`\n");
5540static PyObject *pyrna_struct_get_data(BPy_DummyPointerRNA *self, void * /*closure*/)
5541{
5542 return pyrna_struct_CreatePyObject(&self->ptr.value());
5543}
5544
5546 /* Wrap. */
5547 pyrna_struct_get_rna_type_doc,
5548 "The property type for introspection.\n"
5549 "\n"
5550 ":type: :class:`bpy.types.Property`\n");
5551static PyObject *pyrna_struct_get_rna_type(BPy_PropertyRNA *self, void * /*closure*/)
5552{
5553 PointerRNA tptr = RNA_pointer_create_discrete(nullptr, RNA_Property, self->prop);
5554 return pyrna_struct_Subtype(&tptr);
5555}
5556
5557/*****************************************************************************/
5558/* Python attributes get/set structure: */
5559/*****************************************************************************/
5560
5561static PyGetSetDef pyrna_prop_getseters[] = {
5562 {"id_data",
5563 reinterpret_cast<getter>(pyrna_struct_get_id_data),
5564 static_cast<setter>(nullptr),
5565 pyrna_struct_get_id_data_doc,
5566 nullptr},
5567 {"data",
5568 reinterpret_cast<getter>(pyrna_struct_get_data),
5569 static_cast<setter>(nullptr),
5570 pyrna_struct_get_data_doc,
5571 nullptr},
5572 {"rna_type",
5573 reinterpret_cast<getter>(pyrna_struct_get_rna_type),
5574 static_cast<setter>(nullptr),
5575 pyrna_struct_get_rna_type_doc,
5576 nullptr},
5577 {nullptr, nullptr, nullptr, nullptr, nullptr} /* Sentinel */
5578};
5579
5580static PyGetSetDef pyrna_struct_getseters[] = {
5581 {"id_data",
5582 reinterpret_cast<getter>(pyrna_struct_get_id_data),
5583 static_cast<setter>(nullptr),
5584 pyrna_struct_get_id_data_doc,
5585 nullptr},
5586 {nullptr, nullptr, nullptr, nullptr, nullptr} /* Sentinel */
5587};
5588
5589static PyObject *pyrna_func_doc_get(BPy_FunctionRNA *self, void *closure);
5590
5591static PyGetSetDef pyrna_func_getseters[] = {
5592 {"__doc__",
5593 reinterpret_cast<getter>(pyrna_func_doc_get),
5594 static_cast<setter>(nullptr),
5595 nullptr,
5596 nullptr},
5597 {nullptr, nullptr, nullptr, nullptr, nullptr} /* Sentinel */
5598};
5599
5601 /* Wrap. */
5602 pyrna_prop_collection_keys_doc,
5603 ".. method:: keys()\n"
5604 "\n"
5605 " Return the identifiers of collection members\n"
5606 " (matching Python's dict.keys() functionality).\n"
5607 "\n"
5608 " :return: the identifiers for each member of this collection.\n"
5609 " :rtype: list[str]\n");
5611{
5612 PyObject *ret = PyList_New(0);
5613
5614 BPy_NamePropAsPyObject_Cache nameprop_cache = {nullptr};
5615 RNA_PROP_BEGIN (&self->ptr.value(), itemptr, self->prop) {
5616 if (PyObject *name_py = pyrna_struct_get_nameprop_as_pyobject(&itemptr, nameprop_cache)) {
5617 PyList_APPEND(ret, name_py);
5618 }
5619 }
5621
5622 return ret;
5623}
5624
5626 /* Wrap. */
5627 pyrna_prop_collection_items_doc,
5628 ".. method:: items()\n"
5629 "\n"
5630 " Return the identifiers of collection members\n"
5631 " (matching Python's dict.items() functionality).\n"
5632 "\n"
5633 " :return: (key, value) pairs for each member of this collection.\n"
5634 " :rtype: list[tuple[str, :class:`bpy.types.bpy_struct`]]\n");
5636{
5637 PyObject *ret = PyList_New(0);
5638 int i = 0;
5639
5640 BPy_NamePropAsPyObject_Cache nameprop_cache = {nullptr};
5641 RNA_PROP_BEGIN (&self->ptr.value(), itemptr, self->prop) {
5642 if (!itemptr) [[unlikely]] {
5643 continue;
5644 }
5645 /* Add to Python list. */
5646 PyObject *item = PyTuple_New(2);
5647 PyObject *name_py = pyrna_struct_get_nameprop_as_pyobject(&itemptr, nameprop_cache);
5648 /* Strange to use an index `i` when `name_py` is null, better than excluding it's value.
5649 * In practice this should not happen. */
5650 PyTuple_SET_ITEM(item, 0, name_py ? name_py : PyLong_FromLong(i));
5651 PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
5652
5653 PyList_APPEND(ret, item);
5654
5655 i++;
5656 }
5658
5659 return ret;
5660}
5661
5663 /* Wrap. */
5664 pyrna_prop_collection_values_doc,
5665 ".. method:: values()\n"
5666 "\n"
5667 " Return the values of collection\n"
5668 " (matching Python's dict.values() functionality).\n"
5669 "\n"
5670 " :return: The members of this collection.\n"
5671 " :rtype: list[:class:`bpy.types.bpy_struct` | None]\n");
5673{
5674 /* Re-use slice. */
5675 return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
5676}
5677
5679 /* Wrap. */
5680 pyrna_struct_get_doc,
5681 ".. method:: get(key, default=None, /)\n"
5682 "\n"
5683 " Returns the value of the custom property assigned to key or default\n"
5684 " when not found (matches Python's dictionary function of the same name).\n"
5685 "\n"
5686 " :param key: The key associated with the custom property.\n"
5687 " :type key: str\n"
5688 " :param default: Optional argument for the value to return if\n"
5689 " *key* is not found.\n"
5690 " :type default: Any\n"
5691 " :return: Custom property value or default.\n"
5692 " :rtype: Any\n"
5694static PyObject *pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
5695{
5696 IDProperty *group, *idprop;
5697
5698 const char *key;
5699 PyObject *def = Py_None;
5700
5702
5703 if (!PyArg_ParseTuple(args,
5704 "s" /* `key` */
5705 "|" /* Optional arguments. */
5706 "O" /* `default` */
5707 ":get",
5708 &key,
5709 &def))
5710 {
5711 return nullptr;
5712 }
5713
5714 /* Mostly copied from BPy_IDGroup_Map_GetItem. */
5715 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
5716 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
5717 return nullptr;
5718 }
5719
5720 group = RNA_struct_idprops(&self->ptr.value(), false);
5721 if (group) {
5722 idprop = IDP_GetPropertyFromGroup(group, key);
5723
5724 if (idprop) {
5725 return BPy_IDGroup_WrapData(self->ptr->owner_id, idprop, group);
5726 }
5727 }
5728
5729 return Py_NewRef(def);
5730}
5731
5733 /* Wrap. */
5734 pyrna_struct_pop_doc,
5735 ".. method:: pop(key, default=None, /)\n"
5736 "\n"
5737 " Remove and return the value of the custom property assigned to key or default\n"
5738 " when not found (matches Python's dictionary function of the same name).\n"
5739 "\n"
5740 " :param key: The key associated with the custom property.\n"
5741 " :type key: str\n"
5742 " :param default: Optional argument for the value to return if\n"
5743 " *key* is not found.\n"
5744 " :type default: Any\n"
5745 " :return: Custom property value or default.\n"
5746 " :rtype: Any\n"
5748static PyObject *pyrna_struct_pop(BPy_StructRNA *self, PyObject *args)
5749{
5750 IDProperty *group, *idprop;
5751
5752 const char *key;
5753 PyObject *def = nullptr;
5754
5756
5757 if (!PyArg_ParseTuple(args,
5758 "s" /* `key` */
5759 "|" /* Optional arguments. */
5760 "O" /* `default` */
5761 ":pop",
5762 &key,
5763 &def))
5764 {
5765 return nullptr;
5766 }
5767
5768 /* Mostly copied from BPy_IDGroup_Map_GetItem. */
5769 if (RNA_struct_idprops_check(self->ptr->type) == 0) {
5770 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
5771 return nullptr;
5772 }
5773
5774 group = RNA_struct_idprops(&self->ptr.value(), false);
5775 if (group) {
5776 idprop = IDP_GetPropertyFromGroup(group, key);
5777
5778 if (idprop) {
5779 /* Don't use #BPy_IDGroup_WrapData as the id-property is being removed from the ID. */
5780 PyObject *ret = BPy_IDGroup_MapDataToPy(idprop);
5781 /* Internal error. */
5782 if (ret == nullptr) [[unlikely]] {
5783 return nullptr;
5784 }
5785 IDP_FreeFromGroup(group, idprop);
5786 return ret;
5787 }
5788 }
5789
5790 if (def == nullptr) {
5791 PyErr_SetString(PyExc_KeyError, "key not found");
5792 return nullptr;
5793 }
5794 return Py_NewRef(def);
5795}
5796
5798 /* Wrap. */
5799 pyrna_struct_as_pointer_doc,
5800 ".. method:: as_pointer()\n"
5801 "\n"
5802 " Returns the memory address which holds a pointer to Blender's internal data\n"
5803 "\n"
5804 " :return: int (memory address).\n"
5805 " :rtype: int\n"
5806 "\n"
5807 " .. note:: This is intended only for advanced script writers who need to\n"
5808 " pass blender data to their own C/Python modules.\n");
5810{
5811 return PyLong_FromVoidPtr(self->ptr->data);
5812}
5813
5815 /* Wrap. */
5816 pyrna_prop_collection_get_doc,
5817 ".. method:: get(key, default=None)\n"
5818 "\n"
5819 " Returns the value of the item assigned to key or default when not found\n"
5820 " (matches Python's dictionary function of the same name).\n"
5821 "\n"
5822 " :param key: The identifier for the collection member.\n"
5823 "\n"
5824 " For ``bpy.data`` collections a ``(name, library)`` tuple can also be used.\n"
5825 " *library* is the library filepath or ``None`` for data in the current file.\n"
5826 " :type key: str | tuple[str, str | None]\n"
5827 " :param default: Optional argument for the value to return if\n"
5828 " *key* is not found.\n"
5829 " :type default: Any\n"
5830 " :return: The collection member or default.\n"
5831 " :rtype: :class:`bpy_struct`\n");
5832static PyObject *pyrna_prop_collection_get(BPy_PropertyRNA *self, PyObject *args)
5833{
5834 PointerRNA newptr;
5835
5836 PyObject *key_ob;
5837 PyObject *def = Py_None;
5838
5840
5841 if (!PyArg_ParseTuple(args,
5842 "O" /* `key` */
5843 "|" /* Optional arguments. */
5844 "O" /* `default` */
5845 ":get",
5846 &key_ob,
5847 &def))
5848 {
5849 return nullptr;
5850 }
5851
5852 if (PyUnicode_Check(key_ob)) {
5853 const char *key = PyUnicode_AsUTF8(key_ob);
5854
5855 if (RNA_property_collection_lookup_string(&self->ptr.value(), self->prop, key, &newptr)) {
5856 return pyrna_struct_CreatePyObject(&newptr);
5857 }
5859 "bpy_prop_collection.get") == -1)
5860 {
5861 return nullptr;
5862 }
5863 }
5864 else if (PyTuple_Check(key_ob)) {
5866 self, key_ob, "bpy_prop_collection.get((id, lib))", false);
5867 if (ret) {
5868 return ret;
5869 }
5870 }
5871 else {
5872 PyErr_Format(PyExc_KeyError,
5873 "bpy_prop_collection.get(key, ...): key must be a string or tuple, not %.200s",
5874 Py_TYPE(key_ob)->tp_name);
5875 }
5876
5877 return Py_NewRef(def);
5878}
5879
5881 /* Wrap. */
5882 pyrna_prop_collection_find_doc,
5883 ".. method:: find(key)\n"
5884 "\n"
5885 " Returns the index of a key in a collection or -1 when not found\n"
5886 " (matches Python's string find function of the same name).\n"
5887 "\n"
5888 " :param key: The identifier for the collection member.\n"
5889 " :type key: str\n"
5890 " :return: index of the key.\n"
5891 " :rtype: int\n");
5892static PyObject *pyrna_prop_collection_find(BPy_PropertyRNA *self, PyObject *key_ob)
5893{
5894 Py_ssize_t key_len_ssize;
5895 const char *key = PyUnicode_AsUTF8AndSize(key_ob, &key_len_ssize);
5896 const int key_len = int(key_len_ssize); /* Compare with same type. */
5897
5898 char name[256], *name_ptr;
5899 int name_len;
5900 int i = 0;
5901 int index = -1;
5902
5904
5905 RNA_PROP_BEGIN (&self->ptr.value(), itemptr, self->prop) {
5906 name_ptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &name_len);
5907
5908 if (name_ptr) {
5909 const bool found = (key_len == name_len) && (memcmp(name_ptr, key, key_len) == 0);
5910 if (name != name_ptr) {
5911 MEM_delete(name_ptr);
5912 }
5913 if (found) {
5914 index = i;
5915 break;
5916 }
5917 }
5918
5919 i++;
5920 }
5922
5923 return PyLong_FromLong(index);
5924}
5925
5927 const char *attr,
5928 /* Values to assign. */
5929 RawPropertyType *r_raw_type,
5930 int *r_attr_tot,
5931 bool *r_attr_signed,
5932 bool *r_is_empty)
5933{
5934 PropertyRNA *prop;
5935 bool attr_ok = true;
5936 *r_raw_type = PROP_RAW_UNSET;
5937 *r_attr_tot = 0;
5938 *r_attr_signed = false;
5939 *r_is_empty = true;
5940
5941 /* NOTE: this is fail with zero length lists, so don't let this get called in that case. */
5942 RNA_PROP_BEGIN (&self->ptr.value(), itemptr, self->prop) {
5943 prop = RNA_struct_find_property(&itemptr, attr);
5944 if (prop) {
5945 *r_raw_type = RNA_property_raw_type(prop);
5946 *r_attr_tot = RNA_property_array_length(&itemptr, prop);
5947 *r_attr_signed = (RNA_property_subtype(prop) != PROP_UNSIGNED);
5948 }
5949 else {
5950 attr_ok = false;
5951 }
5952 *r_is_empty = false;
5953 break;
5954 }
5956
5957 return attr_ok;
5958}
5959
5960/* pyrna_prop_collection_foreach_get/set both use this. */
5962 PyObject *args,
5963 const char *function_name,
5964
5965 /* Values to assign. */
5966 const char **r_attr,
5967 PyObject **r_seq,
5968 int *r_tot,
5969 size_t *r_size,
5970 RawPropertyType *r_raw_type,
5971 int *r_attr_tot,
5972 bool *r_attr_signed)
5973{
5974 *r_size = *r_attr_tot = 0;
5975 *r_attr_signed = false;
5976 *r_raw_type = PROP_RAW_UNSET;
5977
5978 if (!PyArg_ParseTuple(args,
5979 "s" /* `attr` */
5980 "O" /* `seq` */
5981 ":foreach_get/set",
5982 r_attr,
5983 r_seq))
5984 {
5985 return -1;
5986 }
5987
5988 if (!PySequence_Check(*r_seq) && PyObject_CheckBuffer(*r_seq)) {
5989 PyErr_Format(PyExc_TypeError,
5990 "%s(..) expected second argument to be a sequence or buffer, not a %.200s",
5991 function_name,
5992 Py_TYPE(*r_seq)->tp_name);
5993 return -1;
5994 }
5995
5996 /* TODO: buffer may not be a sequence! array.array() is though. */
5997 *r_tot = PySequence_Size(*r_seq);
5998
5999 if (*r_tot > 0) {
6000#if 0
6001 /* Avoid a full collection count when all that's needed is to check it's empty. */
6002 int array_tot;
6003
6004 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
6005 array_tot = RNA_property_collection_length(&self->ptr.value(), self->prop);
6006 }
6007 else {
6008 array_tot = RNA_property_array_length(&self->ptr.value(), self->prop);
6009 }
6010 if (array_tot == 0) {
6011 PyErr_Format(PyExc_TypeError,
6012 "%s(..) sequence length mismatch given %d, needed 0",
6013 function_name,
6014 *r_tot);
6015 return -1;
6016 }
6017#endif
6018
6019 bool is_empty = false; /* `array_tot == 0`. */
6020 if (!foreach_attr_type(self, *r_attr, r_raw_type, r_attr_tot, r_attr_signed, &is_empty)) {
6021 PyErr_Format(PyExc_AttributeError,
6022 "%s(..) '%.200s.%200s[...]' elements have no attribute '%.200s'",
6023 function_name,
6024 RNA_struct_identifier(self->ptr->type),
6026 *r_attr);
6027 return -1;
6028 }
6029
6030 if (is_empty) {
6031 PyErr_Format(PyExc_TypeError,
6032 "%s(..) sequence length mismatch given %d, needed 0",
6033 function_name,
6034 *r_tot);
6035 return -1;
6036 }
6037
6038 *r_size = RNA_raw_type_sizeof(*r_raw_type);
6039
6040#if 0
6041 /* This size check does not work as the size check is based on the size of the
6042 * first element and elements in the collection/array can have different sizes
6043 * (i.e. for mixed quad/triangle meshes). See for example issue #111117. */
6044
6045 if ((*r_attr_tot) < 1) {
6046 *r_attr_tot = 1;
6047 }
6048
6049 const int target_tot = array_tot * (*r_attr_tot);
6050
6051 /* rna_access.cc - rna_raw_access(...) uses this same method. */
6052 if (target_tot != (*r_tot)) {
6053 PyErr_Format(PyExc_TypeError,
6054 "%s(..) sequence length mismatch given %d, needed %d",
6055 function_name,
6056 *r_tot,
6057 target_tot);
6058 return -1;
6059 }
6060#endif
6061 }
6062
6063 /* Check 'r_attr_tot' otherwise we don't know if any values were set.
6064 * This isn't ideal because it means running on an empty list may
6065 * fail silently when it's not compatible. */
6066 if (*r_size == 0 && *r_attr_tot != 0) {
6067 PyErr_Format(
6068 PyExc_AttributeError, "%s(..): attribute does not support foreach method", function_name);
6069 return -1;
6070 }
6071 return 0;
6072}
6073
6074static bool foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
6075{
6076 const char f = format ? *format : 'B'; /* B is assumed when not set */
6077
6078 switch (raw_type) {
6079 case PROP_RAW_INT8:
6080 if (attr_signed) {
6081 return (f == 'b') ? true : false;
6082 }
6083 else {
6084 return (f == 'B') ? true : false;
6085 }
6086 case PROP_RAW_CHAR:
6087 case PROP_RAW_UINT8:
6088 return (f == 'B') ? true : false;
6089 case PROP_RAW_SHORT:
6090 if (attr_signed) {
6091 return (f == 'h') ? true : false;
6092 }
6093 else {
6094 return (f == 'H') ? true : false;
6095 }
6096 case PROP_RAW_UINT16:
6097 return (f == 'H') ? true : false;
6098 case PROP_RAW_INT:
6099 if (attr_signed) {
6100 return (f == 'i') ? true : false;
6101 }
6102 else {
6103 return (f == 'I') ? true : false;
6104 }
6105 case PROP_RAW_BOOLEAN:
6106 return (f == '?') ? true : false;
6107 case PROP_RAW_FLOAT:
6108 return (f == 'f') ? true : false;
6109 case PROP_RAW_DOUBLE:
6110 return (f == 'd') ? true : false;
6111 case PROP_RAW_INT64:
6112 if (attr_signed) {
6113 return (f == 'q') ? true : false;
6114 }
6115 else {
6116 return (f == 'Q') ? true : false;
6117 }
6118 case PROP_RAW_UINT64:
6119 return (f == 'Q') ? true : false;
6120 case PROP_RAW_UNSET:
6121 return false;
6122 }
6123
6124 return false;
6125}
6126
6127static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
6128{
6129 PyObject *item = nullptr;
6130 int i = 0, ok = 0;
6131 bool buffer_is_compat;
6132 void *array = nullptr;
6133
6134 /* Get/set both take the same args currently. */
6135 const char *attr;
6136 PyObject *seq;
6137 int tot, attr_tot;
6138 size_t size;
6139 bool attr_signed;
6140 RawPropertyType raw_type;
6141
6142 if (foreach_parse_args(self,
6143 args,
6144 set ? "foreach_set" : "foreach_get",
6145 &attr,
6146 &seq,
6147 &tot,
6148 &size,
6149 &raw_type,
6150 &attr_tot,
6151 &attr_signed) == -1)
6152 {
6153 return nullptr;
6154 }
6155
6156 if (tot == 0) {
6157 Py_RETURN_NONE;
6158 }
6159
6160 if (set) { /* Get the array from python. */
6161 buffer_is_compat = false;
6162 if (PyObject_CheckBuffer(seq)) {
6163 Py_buffer buf;
6164 if (PyObject_GetBuffer(seq, &buf, PyBUF_ND | PyBUF_FORMAT) == -1) {
6165 /* Request failed. A `PyExc_BufferError` will have been raised,
6166 * so clear it to silently fall back to accessing as a sequence. */
6167 PyErr_Clear();
6168 }
6169 else {
6170 /* Check if the buffer matches. */
6171
6172 buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
6173
6174 if (buffer_is_compat) {
6176 nullptr, &self->ptr.value(), self->prop, attr, buf.buf, raw_type, tot);
6177 }
6178
6179 PyBuffer_Release(&buf);
6180 }
6181 }
6182
6183 /* Could not use the buffer, fall back to sequence. */
6184 if (!buffer_is_compat) {
6185 array = PyMem_Malloc(size * tot);
6186
6187 for (; i < tot; i++) {
6188 item = PySequence_GetItem(seq, i);
6189 switch (raw_type) {
6190 case PROP_RAW_CHAR:
6191 (static_cast<char *>(array))[i] = char(PyC_Long_AsU8(item));
6192 break;
6193 case PROP_RAW_INT8:
6194 (static_cast<int8_t *>(array))[i] = PyC_Long_AsI8(item);
6195 break;
6196 case PROP_RAW_UINT8:
6197 (static_cast<uint8_t *>(array))[i] = PyC_Long_AsU8(item);
6198 break;
6199 case PROP_RAW_SHORT:
6200 (static_cast<short *>(array))[i] = short(PyC_Long_AsI16(item));
6201 break;
6202 case PROP_RAW_UINT16:
6203 (static_cast<uint16_t *>(array))[i] = PyC_Long_AsU16(item);
6204 break;
6205 case PROP_RAW_INT:
6206 (static_cast<int *>(array))[i] = int(PyC_Long_AsI32(item));
6207 break;
6208 case PROP_RAW_BOOLEAN:
6209 (static_cast<bool *>(array))[i] = bool(PyC_Long_AsBool(item));
6210 break;
6211 case PROP_RAW_FLOAT:
6212 (static_cast<float *>(array))[i] = float(PyFloat_AsDouble(item));
6213 break;
6214 case PROP_RAW_DOUBLE:
6215 (static_cast<double *>(array))[i] = PyFloat_AsDouble(item);
6216 break;
6217 case PROP_RAW_INT64:
6218 (static_cast<int64_t *>(array))[i] = PyC_Long_AsI64(item);
6219 break;
6220 case PROP_RAW_UINT64:
6221 (static_cast<uint64_t *>(array))[i] = PyC_Long_AsU64(item);
6222 break;
6223 case PROP_RAW_UNSET:
6224 /* Should never happen. */
6225 BLI_assert_msg(0, "Invalid array type - set");
6226 break;
6227 }
6228
6229 Py_DECREF(item);
6230 }
6231
6233 nullptr, &self->ptr.value(), self->prop, attr, array, raw_type, tot);
6234 }
6235 }
6236 else {
6237 buffer_is_compat = false;
6238 if (PyObject_CheckBuffer(seq)) {
6239 Py_buffer buf;
6240 /* Writable, the buffer is filled in below. */
6241 if (PyObject_GetBuffer(seq, &buf, PyBUF_ND | PyBUF_FORMAT | PyBUF_WRITABLE) == -1) {
6242 /* Request failed. A `PyExc_BufferError` will have been raised,
6243 * so clear it to silently fall back to accessing as a sequence. */
6244 PyErr_Clear();
6245 }
6246 else {
6247 /* Check if the buffer matches. */
6248
6249 buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
6250
6251 if (buffer_is_compat) {
6253 nullptr, &self->ptr.value(), self->prop, attr, buf.buf, raw_type, tot);
6254 }
6255
6256 PyBuffer_Release(&buf);
6257 }
6258 }
6259
6260 /* Could not use the buffer, fall back to sequence. */
6261 if (!buffer_is_compat) {
6262 array = PyMem_Malloc(size * tot);
6263
6265 nullptr, &self->ptr.value(), self->prop, attr, array, raw_type, tot);
6266
6267 if (!ok) {
6268 /* Skip the loop. */
6269 i = tot;
6270 }
6271
6272 for (; i < tot; i++) {
6273
6274 switch (raw_type) {
6275 case PROP_RAW_CHAR:
6276 item = PyLong_FromLong(long((static_cast<char *>(array))[i]));
6277 break;
6278 case PROP_RAW_INT8:
6279 item = PyLong_FromLong(long((static_cast<int8_t *>(array))[i]));
6280 break;
6281 case PROP_RAW_UINT8:
6282 item = PyLong_FromLong(long((static_cast<uint8_t *>(array))[i]));
6283 break;
6284 case PROP_RAW_SHORT:
6285 item = PyLong_FromLong(long((static_cast<short *>(array))[i]));
6286 break;
6287 case PROP_RAW_UINT16:
6288 item = PyLong_FromLong(long((static_cast<uint16_t *>(array))[i]));
6289 break;
6290 case PROP_RAW_INT:
6291 item = PyLong_FromLong(long((static_cast<int *>(array))[i]));
6292 break;
6293 case PROP_RAW_FLOAT:
6294 item = PyFloat_FromDouble(double((static_cast<float *>(array))[i]));
6295 break;
6296 case PROP_RAW_DOUBLE:
6297 item = PyFloat_FromDouble((static_cast<double *>(array))[i]);
6298 break;
6299 case PROP_RAW_BOOLEAN:
6300 item = PyBool_FromLong(long((static_cast<bool *>(array))[i]));
6301 break;
6302 case PROP_RAW_INT64:
6303 item = PyLong_FromLongLong((static_cast<int64_t *>(array))[i]);
6304 break;
6305 case PROP_RAW_UINT64:
6306 item = PyLong_FromUnsignedLongLong((static_cast<uint64_t *>(array))[i]);
6307 break;
6308 default: /* PROP_RAW_UNSET */
6309 /* Should never happen. */
6310 BLI_assert_msg(0, "Invalid array type - get");
6311 item = Py_None;
6312 Py_INCREF(item);
6313 break;
6314 }
6315
6316 PySequence_SetItem(seq, i, item);
6317 Py_DECREF(item);
6318 }
6319 }
6320 }
6321
6322 if (array) {
6323 PyMem_Free(array);
6324 }
6325
6326 if (PyErr_Occurred()) {
6327 /* Maybe we could make our own error. */
6328 PyErr_Print();
6329 PyErr_SetString(PyExc_TypeError, "couldn't access the py sequence");
6330 return nullptr;
6331 }
6332 if (!ok) {
6333 PyErr_SetString(PyExc_RuntimeError, "internal error setting the array");
6334 return nullptr;
6335 }
6336
6337 if (set) {
6338 RNA_property_update(BPY_context_get(), &self->ptr.value(), self->prop);
6339 }
6340 Py_RETURN_NONE;
6341}
6342
6344 /* Wrap. */
6345 pyrna_prop_collection_foreach_get_doc,
6346 ".. method:: foreach_get(attr, seq)\n"
6347 "\n"
6348 " Fast access to a basic-type attribute within a collection.\n"
6349 "\n"
6350 " :param attr: Name of the item attribute to read (for example ``co``, ``normal`` or\n"
6351 " ``select``). The attribute must be a basic type (bool, int or float).\n"
6352 "\n"
6353 " For geometry attribute types, see :attr:`Attribute.data_type`.\n"
6354 " :type attr: str\n"
6355 " :param seq: Writable sequence or buffer receiving flattened values.\n"
6356 " For array attributes, the length must be ``len(collection) * array_length``.\n"
6357 " :type seq: MutableSequence[bool | int | float] | Buffer\n");
6358static PyObject *pyrna_prop_collection_foreach_get(BPy_PropertyRNA *self, PyObject *args)
6359{
6361
6362 return foreach_getset(self, args, 0);
6363}
6364
6366 /* Wrap. */
6367 pyrna_prop_collection_foreach_set_doc,
6368 ".. method:: foreach_set(attr, seq)\n"
6369 "\n"
6370 " Fast access to a basic-type attribute within a collection.\n"
6371 "\n"
6372 " :param attr: Name of the item attribute to write (for example ``co`` or\n"
6373 " ``select``). The attribute must be a basic type (bool, int or float).\n"
6374 "\n"
6375 " For geometry attribute types, see :attr:`Attribute.data_type`.\n"
6376 " :type attr: str\n"
6377 " :param seq: Sequence or buffer containing flattened values.\n"
6378 " For array attributes, the length must be ``len(collection) * array_length``.\n"
6379 " :type seq: Sequence[bool | int | float] | Buffer\n");
6380static PyObject *pyrna_prop_collection_foreach_set(BPy_PropertyRNA *self, PyObject *args)
6381{
6383
6384 return foreach_getset(self, args, 1);
6385}
6386
6388 PyObject *args,
6389 const bool do_set)
6390{
6391 PyObject *item = nullptr;
6392 Py_ssize_t i, seq_size, size;
6393 void *array = nullptr;
6394 const PropertyType prop_type = RNA_property_type(self->prop);
6395
6396 /* Get/set both take the same args currently. */
6397 PyObject *seq;
6398
6399 if (!ELEM(prop_type, PROP_INT, PROP_FLOAT)) {
6400 PyErr_SetString(PyExc_TypeError, "foreach_get/set available only for int and float");
6401 return nullptr;
6402 }
6403
6404 if (!PyArg_ParseTuple(args,
6405 "O" /* `seq` */
6406 ":foreach_get/set",
6407 &seq))
6408 {
6409 return nullptr;
6410 }
6411
6412 if (!PySequence_Check(seq) && PyObject_CheckBuffer(seq)) {
6413 PyErr_Format(
6414 PyExc_TypeError,
6415 "foreach_get/set expected second argument to be a sequence or buffer, not a %.200s",
6416 Py_TYPE(seq)->tp_name);
6417 return nullptr;
6418 }
6419
6420 /* NOTE: in this case it's important to use the flat-array size and *not* the result of
6421 * `len()`, which uses #pyrna_prop_array_length, see !116457 for details. */
6422 size = RNA_property_array_length(&self->ptr.value(), self->prop);
6423 seq_size = PySequence_Size(seq);
6424
6425 if (size != seq_size) {
6426 PyErr_Format(PyExc_TypeError, "expected sequence size %d, got %d", size, seq_size);
6427 return nullptr;
6428 }
6429
6430 Py_buffer buf;
6431 /* Writable when reading into the buffer, `do_set` only reads from it. */
6432 if (PyObject_GetBuffer(seq, &buf, PyBUF_ND | PyBUF_FORMAT | (do_set ? 0 : PyBUF_WRITABLE)) == -1)
6433 {
6434 PyErr_Clear();
6435
6436 switch (prop_type) {
6437 case PROP_INT:
6438 array = PyMem_Malloc(sizeof(int) * size);
6439 if (do_set) {
6440 for (i = 0; i < size; i++) {
6441 item = PySequence_GetItem(seq, i);
6442 (static_cast<int *>(array))[i] = int(PyLong_AsLong(item));
6443 Py_DECREF(item);
6444 }
6445
6447 &self->ptr.value(), self->prop, static_cast<const int *>(array));
6448 }
6449 else {
6450 RNA_property_int_get_array(&self->ptr.value(), self->prop, static_cast<int *>(array));
6451
6452 for (i = 0; i < size; i++) {
6453 item = PyLong_FromLong(long((static_cast<int *>(array))[i]));
6454 PySequence_SetItem(seq, i, item);
6455 Py_DECREF(item);
6456 }
6457 }
6458
6459 break;
6460 case PROP_FLOAT:
6461 array = PyMem_Malloc(sizeof(float) * size);
6462 if (do_set) {
6463 for (i = 0; i < size; i++) {
6464 item = PySequence_GetItem(seq, i);
6465 (static_cast<float *>(array))[i] = float(PyFloat_AsDouble(item));
6466 Py_DECREF(item);
6467 }
6468
6470 &self->ptr.value(), self->prop, static_cast<const float *>(array));
6471 }
6472 else {
6474 &self->ptr.value(), self->prop, static_cast<float *>(array));
6475
6476 for (i = 0; i < size; i++) {
6477 item = PyFloat_FromDouble(double((static_cast<float *>(array))[i]));
6478 PySequence_SetItem(seq, i, item);
6479 Py_DECREF(item);
6480 }
6481 }
6482 break;
6483 case PROP_BOOLEAN:
6484 case PROP_STRING:
6485 case PROP_ENUM:
6486 case PROP_POINTER:
6487 case PROP_COLLECTION:
6488 /* Should never happen. */
6490 break;
6491 }
6492
6493 PyMem_Free(array);
6494
6495 if (PyErr_Occurred()) {
6496 /* Maybe we could make our own error. */
6497 PyErr_Print();
6498 PyErr_SetString(PyExc_TypeError, "couldn't access the py sequence");
6499 return nullptr;
6500 }
6501 }
6502 else {
6503 const char f = buf.format ? buf.format[0] : 0;
6504 if ((prop_type == PROP_INT && (buf.itemsize != sizeof(int) || !ELEM(f, 'l', 'i'))) ||
6505 (prop_type == PROP_FLOAT && (buf.itemsize != sizeof(float) || f != 'f')))
6506 {
6507 PyBuffer_Release(&buf);
6508 PyErr_Format(PyExc_TypeError, "incorrect sequence item type: %s", buf.format);
6509 return nullptr;
6510 }
6511
6512 switch (prop_type) {
6513 case PROP_INT:
6514 if (do_set) {
6516 &self->ptr.value(), self->prop, static_cast<const int *>(buf.buf));
6517 }
6518 else {
6519 RNA_property_int_get_array(&self->ptr.value(), self->prop, static_cast<int *>(buf.buf));
6520 }
6521 break;
6522 case PROP_FLOAT:
6523 if (do_set) {
6525 &self->ptr.value(), self->prop, static_cast<const float *>(buf.buf));
6526 }
6527 else {
6529 &self->ptr.value(), self->prop, static_cast<float *>(buf.buf));
6530 }
6531 break;
6532 case PROP_BOOLEAN:
6533 case PROP_STRING:
6534 case PROP_ENUM:
6535 case PROP_POINTER:
6536 case PROP_COLLECTION:
6537 /* Should never happen. */
6539 break;
6540 }
6541
6542 PyBuffer_Release(&buf);
6543 }
6544
6545 Py_RETURN_NONE;
6546}
6547
6549 /* Wrap. */
6550 pyrna_prop_array_foreach_get_doc,
6551 ".. method:: foreach_get(seq)\n"
6552 "\n"
6553 " This is a function to give fast access to array data.\n"
6554 "\n"
6555 " :param seq: Buffer to read element values into, must match the length of this array.\n"
6556 " :type seq: MutableSequence[Any]\n");
6557static PyObject *pyrna_prop_array_foreach_get(BPy_PropertyArrayRNA *self, PyObject *args)
6558{
6560
6561 return pyprop_array_foreach_getset(self, args, false);
6562}
6563
6565 /* Wrap. */
6566 pyrna_prop_array_foreach_set_doc,
6567 ".. method:: foreach_set(seq)\n"
6568 "\n"
6569 " This is a function to give fast access to array data.\n"
6570 "\n"
6571 " :param seq: Element values to write, must match the length of this array.\n"
6572 " :type seq: Sequence[Any]\n");
6573static PyObject *pyrna_prop_array_foreach_set(BPy_PropertyArrayRNA *self, PyObject *args)
6574{
6576
6577 return pyprop_array_foreach_getset(self, args, true);
6578}
6579
6580/* A bit of a kludge, make a list out of a collection or array,
6581 * then return the list's iter function, not especially fast, but convenient for now. */
6583{
6584 /* Try get values from a collection. */
6585 PyObject *ret;
6586 PyObject *iter = nullptr;
6587 int len;
6588
6590
6592 ret = pyrna_prop_array_subscript_slice(self, &self->ptr.value(), self->prop, 0, 1, len, len);
6593
6594 /* we know this is a list so no need to PyIter_Check
6595 * otherwise it could be nullptr (unlikely) if conversion failed */
6596 if (ret) {
6597 iter = PyObject_GetIter(ret);
6598 Py_DECREF(ret);
6599 }
6600
6601 return iter;
6602}
6603
6604static PyObject *pyrna_prop_collection_iter(PyObject *self);
6605
6606#ifndef USE_PYRNA_ITER
6607static PyObject *pyrna_prop_collection_iter(PyObject *self)
6608{
6609 BPy_PropertyRNA *self_property = reinterpret_cast<BPy_PropertyRNA *>(self);
6610
6611 /* Try get values from a collection. */
6612 PyObject *ret;
6613 PyObject *iter = nullptr;
6614 ret = pyrna_prop_collection_values(self_property);
6615
6616 /* we know this is a list so no need to PyIter_Check
6617 * otherwise it could be nullptr (unlikely) if conversion failed */
6618 if (ret) {
6619 iter = PyObject_GetIter(ret);
6620 Py_DECREF(ret);
6621 }
6622
6623 return iter;
6624}
6625#endif /* # !USE_PYRNA_ITER */
6626
6627#ifdef __GNUC__
6628# ifdef __clang__
6629# pragma clang diagnostic push
6630# pragma clang diagnostic ignored "-Wcast-function-type"
6631# else
6632# pragma GCC diagnostic push
6633# pragma GCC diagnostic ignored "-Wcast-function-type"
6634# endif
6635#endif
6636
6637static PyMethodDef pyrna_struct_methods[] = {
6638
6639 /* Only for PointerRNA's with ID'props. */
6640 {"keys", reinterpret_cast<PyCFunction>(pyrna_struct_keys), METH_NOARGS, pyrna_struct_keys_doc},
6641 {"values",
6642 reinterpret_cast<PyCFunction>(pyrna_struct_values),
6643 METH_NOARGS,
6644 pyrna_struct_values_doc},
6645 {"items",
6646 reinterpret_cast<PyCFunction>(pyrna_struct_items),
6647 METH_NOARGS,
6648 pyrna_struct_items_doc},
6649
6650 {"get", reinterpret_cast<PyCFunction>(pyrna_struct_get), METH_VARARGS, pyrna_struct_get_doc},
6651 {"pop", reinterpret_cast<PyCFunction>(pyrna_struct_pop), METH_VARARGS, pyrna_struct_pop_doc},
6652
6653 {"as_pointer",
6654 reinterpret_cast<PyCFunction>(pyrna_struct_as_pointer),
6655 METH_NOARGS,
6656 pyrna_struct_as_pointer_doc},
6657
6658 /* `bpy_rna_anim.cc` */
6659 {"keyframe_insert",
6660 reinterpret_cast<PyCFunction>(pyrna_struct_keyframe_insert),
6661 METH_VARARGS | METH_KEYWORDS,
6663 {"keyframe_delete",
6664 reinterpret_cast<PyCFunction>(pyrna_struct_keyframe_delete),
6665 METH_VARARGS | METH_KEYWORDS,
6667 {"driver_add",
6668 reinterpret_cast<PyCFunction>(pyrna_struct_driver_add),
6669 METH_VARARGS,
6671 {"driver_remove",
6672 reinterpret_cast<PyCFunction>(pyrna_struct_driver_remove),
6673 METH_VARARGS,
6675
6676 {"is_property_set",
6677 reinterpret_cast<PyCFunction>(pyrna_struct_is_property_set),
6678 METH_VARARGS | METH_KEYWORDS,
6679 pyrna_struct_is_property_set_doc},
6680 {"property_unset",
6681 reinterpret_cast<PyCFunction>(pyrna_struct_property_unset),
6682 METH_VARARGS,
6683 pyrna_struct_property_unset_doc},
6684 {"is_property_hidden",
6685 reinterpret_cast<PyCFunction>(pyrna_struct_is_property_hidden),
6686 METH_VARARGS,
6687 pyrna_struct_is_property_hidden_doc},
6688 {"is_property_readonly",
6689 reinterpret_cast<PyCFunction>(pyrna_struct_is_property_readonly),
6690 METH_VARARGS,
6691 pyrna_struct_is_property_readonly_doc},
6692 {"is_property_overridable_library",
6693 reinterpret_cast<PyCFunction>(pyrna_struct_is_property_overridable_library),
6694 METH_VARARGS,
6695 pyrna_struct_is_property_overridable_library_doc},
6696 {"property_overridable_library_set",
6697 reinterpret_cast<PyCFunction>(pyrna_struct_property_overridable_library_set),
6698 METH_VARARGS,
6699 pyrna_struct_property_overridable_library_set_doc},
6700 {"path_resolve",
6701 reinterpret_cast<PyCFunction>(pyrna_struct_path_resolve),
6702 METH_VARARGS,
6703 pyrna_struct_path_resolve_doc},
6704 {"path_from_id",
6705 reinterpret_cast<PyCFunction>(pyrna_struct_path_from_id),
6706 METH_VARARGS,
6707 pyrna_struct_path_from_id_doc},
6708 {"path_from_module",
6709 reinterpret_cast<PyCFunction>(pyrna_struct_path_from_module),
6710 METH_VARARGS,
6711 pyrna_struct_path_from_module_doc},
6712 {"type_recast",
6713 reinterpret_cast<PyCFunction>(pyrna_struct_type_recast),
6714 METH_NOARGS,
6715 pyrna_struct_type_recast_doc},
6716 {"bl_rna_get_subclass_py",
6717 static_cast<PyCFunction>(pyrna_struct_bl_rna_get_subclass_py),
6718 METH_VARARGS | METH_CLASS,
6719 pyrna_struct_bl_rna_get_subclass_py_doc},
6720 {"bl_rna_get_subclass",
6721 static_cast<PyCFunction>(pyrna_struct_bl_rna_get_subclass),
6722 METH_VARARGS | METH_CLASS,
6723 pyrna_struct_bl_rna_get_subclass_doc},
6724 {"rna_ancestors",
6725 reinterpret_cast<PyCFunction>(pyrna_struct_get_ancestors),
6726 METH_NOARGS,
6727 pyrna_struct_get_ancestors_doc},
6728 {"__dir__", reinterpret_cast<PyCFunction>(pyrna_struct_dir), METH_NOARGS, nullptr},
6729 {"id_properties_ensure",
6730 reinterpret_cast<PyCFunction>(pyrna_struct_id_properties_ensure),
6731 METH_NOARGS,
6732 pyrna_struct_id_properties_ensure_doc},
6733 {"id_properties_clear",
6734 reinterpret_cast<PyCFunction>(pyrna_struct_id_properties_clear),
6735 METH_NOARGS,
6736 pyrna_struct_id_properties_clear_doc},
6737 {"id_properties_ui",
6738 reinterpret_cast<PyCFunction>(pyrna_struct_id_properties_ui),
6739 METH_VARARGS,
6740 pyrna_struct_id_properties_ui_doc},
6741
6742/* experimental */
6743/* unused for now */
6744#if 0
6745 {"callback_add", (PyCFunction)pyrna_callback_add, METH_VARARGS, nullptr},
6746 {"callback_remove", (PyCFunction)pyrna_callback_remove, METH_VARARGS, nullptr},
6747
6748 {"callback_add",
6749 (PyCFunction)pyrna_callback_classmethod_add,
6750 METH_VARARGS | METH_CLASS,
6751 nullptr},
6752 {"callback_remove",
6754 METH_VARARGS | METH_CLASS,
6755 nullptr},
6756#endif
6757 {nullptr, nullptr, 0, nullptr},
6758};
6759
6760static PyMethodDef pyrna_prop_methods[] = {
6761 {"path_from_id",
6762 reinterpret_cast<PyCFunction>(pyrna_prop_path_from_id),
6763 METH_NOARGS,
6764 pyrna_prop_path_from_id_doc},
6765 {"path_from_module",
6766 reinterpret_cast<PyCFunction>(pyrna_prop_path_from_module),
6767 METH_NOARGS,
6768 pyrna_prop_path_from_module_doc},
6769 {"as_bytes",
6770 reinterpret_cast<PyCFunction>(pyrna_prop_as_bytes),
6771 METH_NOARGS,
6772 pyrna_prop_as_bytes_doc},
6773 {"update",
6774 reinterpret_cast<PyCFunction>(pyrna_prop_update),
6775 METH_NOARGS,
6776 pyrna_prop_update_doc},
6777 {"__dir__", reinterpret_cast<PyCFunction>(pyrna_prop_dir), METH_NOARGS, nullptr},
6778 {nullptr, nullptr, 0, nullptr},
6779};
6780
6781static PyMethodDef pyrna_prop_array_methods[] = {
6782 {"foreach_get",
6783 reinterpret_cast<PyCFunction>(pyrna_prop_array_foreach_get),
6784 METH_VARARGS,
6785 pyrna_prop_array_foreach_get_doc},
6786 {"foreach_set",
6787 reinterpret_cast<PyCFunction>(pyrna_prop_array_foreach_set),
6788 METH_VARARGS,
6789 pyrna_prop_array_foreach_set_doc},
6790
6791 {nullptr, nullptr, 0, nullptr},
6792};
6793
6794static PyMethodDef pyrna_prop_collection_methods[] = {
6795 {"foreach_get",
6796 reinterpret_cast<PyCFunction>(pyrna_prop_collection_foreach_get),
6797 METH_VARARGS,
6798 pyrna_prop_collection_foreach_get_doc},
6799 {"foreach_set",
6800 reinterpret_cast<PyCFunction>(pyrna_prop_collection_foreach_set),
6801 METH_VARARGS,
6802 pyrna_prop_collection_foreach_set_doc},
6803
6804 {"keys",
6805 reinterpret_cast<PyCFunction>(pyrna_prop_collection_keys),
6806 METH_NOARGS,
6807 pyrna_prop_collection_keys_doc},
6808 {"items",
6809 reinterpret_cast<PyCFunction>(pyrna_prop_collection_items),
6810 METH_NOARGS,
6811 pyrna_prop_collection_items_doc},
6812 {"values",
6813 reinterpret_cast<PyCFunction>(pyrna_prop_collection_values),
6814 METH_NOARGS,
6815 pyrna_prop_collection_values_doc},
6816
6817 {"get",
6818 reinterpret_cast<PyCFunction>(pyrna_prop_collection_get),
6819 METH_VARARGS,
6820 pyrna_prop_collection_get_doc},
6821 {"find",
6822 reinterpret_cast<PyCFunction>(pyrna_prop_collection_find),
6823 METH_O,
6824 pyrna_prop_collection_find_doc},
6825 {nullptr, nullptr, 0, nullptr},
6826};
6827
6829 {"add",
6830 reinterpret_cast<PyCFunction>(pyrna_prop_collection_idprop_add),
6831 METH_NOARGS,
6832 pyrna_prop_collection_idprop_add_doc},
6833 {"remove",
6834 reinterpret_cast<PyCFunction>(pyrna_prop_collection_idprop_remove),
6835 METH_O,
6836 pyrna_prop_collection_idprop_remove_doc},
6837 {"clear",
6838 reinterpret_cast<PyCFunction>(pyrna_prop_collection_idprop_clear),
6839 METH_NOARGS,
6840 pyrna_prop_collection_idprop_clear_doc},
6841 {"move",
6842 reinterpret_cast<PyCFunction>(pyrna_prop_collection_idprop_move),
6843 METH_VARARGS,
6844 pyrna_prop_collection_idprop_move_doc},
6845 {nullptr, nullptr, 0, nullptr},
6846};
6847
6848#ifdef __GNUC__
6849# ifdef __clang__
6850# pragma clang diagnostic pop
6851# else
6852# pragma GCC diagnostic pop
6853# endif
6854#endif
6855
6856static PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
6857{
6858 PyObject *ret;
6859 const int type = RNA_property_type(prop);
6860 const int flag = RNA_property_flag(prop);
6861 const int flag_parameter = RNA_parameter_flag(prop);
6862
6863 if (RNA_property_array_check(prop)) {
6864 int a, len;
6865
6866 if (flag & PROP_DYNAMIC) {
6867 ParameterDynAlloc *data_alloc = static_cast<ParameterDynAlloc *>(data);
6868 len = data_alloc->array_tot;
6869 data = data_alloc->array;
6870 }
6871 else {
6872 len = RNA_property_array_length(ptr, prop);
6873 }
6874
6875 /* Resolve the array from a new Python type. */
6876
6877 /* TODO(Kazanbas): make multi-dimensional sequences here. */
6878
6879 switch (type) {
6880 case PROP_BOOLEAN:
6881 ret = PyTuple_New(len);
6882 for (a = 0; a < len; a++) {
6883 PyTuple_SET_ITEM(ret, a, PyBool_FromLong(((bool *)data)[a]));
6884 }
6885 break;
6886 case PROP_INT:
6887 ret = PyTuple_New(len);
6888 for (a = 0; a < len; a++) {
6889 PyTuple_SET_ITEM(ret, a, PyLong_FromLong(((int *)data)[a]));
6890 }
6891 break;
6892 case PROP_FLOAT:
6893 switch (RNA_property_subtype(prop)) {
6894#ifdef USE_MATHUTILS
6896 ret = Vector_CreatePyObject(static_cast<const float *>(data), len, nullptr);
6897 break;
6898 case PROP_MATRIX:
6899 if (len == 16) {
6900 ret = Matrix_CreatePyObject(static_cast<const float *>(data), 4, 4, nullptr);
6901 break;
6902 }
6903 else if (len == 9) {
6904 ret = Matrix_CreatePyObject(static_cast<const float *>(data), 3, 3, nullptr);
6905 break;
6906 }
6908#endif
6909 default:
6910 ret = PyTuple_New(len);
6911 for (a = 0; a < len; a++) {
6912 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble(((float *)data)[a]));
6913 }
6914 break;
6915 }
6916 break;
6917 default:
6918 PyErr_Format(
6919 PyExc_TypeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
6920 ret = nullptr;
6921 break;
6922 }
6923 }
6924 else {
6925 /* See if we can coerce into a python type - PropertyType. */
6926 switch (type) {
6927 case PROP_BOOLEAN:
6928 ret = PyBool_FromLong(*static_cast<bool *>(data));
6929 break;
6930 case PROP_INT:
6931 ret = PyLong_FromLong(*static_cast<int *>(data));
6932 break;
6933 case PROP_FLOAT:
6934 ret = PyFloat_FromDouble(*static_cast<float *>(data));
6935 break;
6936 case PROP_STRING: {
6937 const char *data_ch;
6938 const int subtype = RNA_property_subtype(prop);
6939 size_t data_ch_len;
6940
6941 if (flag & PROP_DYNAMIC) {
6942 ParameterDynAlloc *data_alloc = static_cast<ParameterDynAlloc *>(data);
6943 data_ch = static_cast<const char *>(data_alloc->array);
6944 data_ch_len = data_alloc->array_tot;
6945 BLI_assert((data_ch == nullptr) || strlen(data_ch) == data_ch_len);
6946 }
6947 else {
6948 data_ch = (flag & PROP_THICK_WRAP) ? static_cast<char *>(data) :
6949 *static_cast<char **>(data);
6950 data_ch_len = data_ch ? strlen(data_ch) : 0;
6951 }
6952
6953 if (data_ch == nullptr) [[unlikely]] {
6954 BLI_assert((flag & PROP_NEVER_NULL) == 0);
6955 ret = Py_None;
6956 Py_INCREF(ret);
6957 }
6958#ifdef USE_STRING_COERCE
6959 else if (subtype == PROP_BYTESTRING) {
6960 ret = PyBytes_FromStringAndSize(data_ch, data_ch_len);
6961 }
6962 else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
6963 ret = PyC_UnicodeFromBytesAndSize(data_ch, data_ch_len);
6964 }
6965 else {
6966 ret = PyUnicode_FromStringAndSize(data_ch, data_ch_len);
6967 }
6968#else
6969 else if (subtype == PROP_BYTESTRING) {
6970 ret = PyBytes_FromString(buf);
6971 }
6972 else {
6973 ret = PyUnicode_FromString(data_ch);
6974 }
6975#endif
6976
6977 break;
6978 }
6979 case PROP_ENUM: {
6980 ret = pyrna_enum_to_py(ptr, prop, *static_cast<int *>(data));
6981 break;
6982 }
6983 case PROP_POINTER: {
6984 PointerRNA newptr;
6985 PointerRNA *newptr_p = nullptr;
6986 StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
6987
6988 if (flag_parameter & PARM_RNAPTR) {
6989 if (flag & PROP_THICK_WRAP) {
6990 /* `data` points to a PointerRNA. */
6991 newptr_p = static_cast<PointerRNA *>(data);
6992 }
6993 else {
6994 /* `data` points to a pointer to a PointerRNA. */
6995 newptr_p = *reinterpret_cast<PointerRNA **>(data);
6996 }
6997 }
6998 else {
6999 if (RNA_struct_is_ID(ptype)) {
7000 newptr = RNA_id_pointer_create(static_cast<ID *>(*static_cast<void **>(data)));
7001 }
7002 else {
7003 /* NOTE: this is taken from the function's ID pointer
7004 * and will break if a function returns a pointer from
7005 * another ID block, watch this! - it should at least be
7006 * easy to debug since they are all ID's */
7008 ptr->owner_id, ptype, *static_cast<void **>(data));
7009 }
7010 newptr_p = &newptr;
7011 }
7012
7013 if (*newptr_p) {
7014 ret = pyrna_struct_CreatePyObject(newptr_p);
7015 }
7016 else {
7017 ret = Py_None;
7018 Py_INCREF(ret);
7019 }
7020 break;
7021 }
7022 case PROP_COLLECTION: {
7023 CollectionVector *lb = static_cast<CollectionVector *>(data);
7024 ret = PyList_New(0);
7025 for (PointerRNA &ptr_iter : lb->items) {
7026 PyList_APPEND(ret, pyrna_struct_CreatePyObject(&ptr_iter));
7027 }
7028 break;
7029 }
7030 default:
7031 PyErr_Format(PyExc_TypeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
7032 ret = nullptr;
7033 break;
7034 }
7035 }
7036
7037 return ret;
7038}
7039
7040inline static PyObject *kwnames_get_item_string(PyObject *const *args,
7041 Py_ssize_t nargs,
7042 PyObject *kwnames,
7043 Py_ssize_t nkw,
7044 const char *parm_name)
7045{
7046 const Py_ssize_t parm_name_len = strlen(parm_name);
7047
7048 for (Py_ssize_t i = 0; i < nkw; i++) {
7049 PyObject *key = PyTuple_GET_ITEM(kwnames, i); /* Borrow reference. */
7050 if (PyUnicode_Check(key)) {
7051 Py_ssize_t key_buf_len;
7052 const char *key_buf = PyUnicode_AsUTF8AndSize(key, &key_buf_len);
7053 if ((parm_name_len == key_buf_len) && (memcmp(parm_name, key_buf, parm_name_len) == 0)) {
7054 return args[nargs + i]; /* Borrow reference. */
7055 }
7056 }
7057 }
7058
7059 return nullptr;
7060}
7061
7066 PropertyRNA *parm,
7067 const int parm_index,
7068 char *error,
7069 const size_t error_maxncpy)
7070{
7071 PointerRNA *self_ptr = &self->ptr.value();
7072 FunctionRNA *self_func = self->func;
7073 if (parm_index == -1) {
7074 BLI_snprintf_utf8(error,
7075 error_maxncpy,
7076 "%.200s.%.200s(): error with keyword argument \"%.200s\" - ",
7077 RNA_struct_identifier(self_ptr->type),
7078 RNA_function_identifier(self_func),
7080 }
7081 else {
7082 BLI_snprintf_utf8(error,
7083 error_maxncpy,
7084 "%.200s.%.200s(): error with argument %d, \"%.200s\" - ",
7085 RNA_struct_identifier(self_ptr->type),
7086 RNA_function_identifier(self_func),
7087 parm_index + 1,
7089 }
7090}
7091
7097static PyObject *pyrna_func_vectorcall(PyObject *callable,
7098 PyObject *const *args,
7099 size_t nargsf,
7100 PyObject *kwnames)
7101{
7102 /* NOTE: both BPy_StructRNA and BPy_PropertyRNA can be used here. */
7103 BPy_FunctionRNA *self = reinterpret_cast<BPy_FunctionRNA *>(callable);
7104 PointerRNA *self_ptr = &self->ptr.value();
7105 FunctionRNA *self_func = self->func;
7106
7107 ParameterList parms;
7108 ParameterIterator iter;
7109 PropertyRNA *parm;
7110 PyObject *ret, *item;
7111 int i, parms_len, ret_len, flag_parameter, err = 0, kw_tot = 0;
7112 bool kw_arg;
7113
7114 PropertyRNA *pret_single = nullptr;
7115 void *retdata_single = nullptr;
7116
7117 /* enable this so all strings are copied and freed after calling.
7118 * this exposes bugs where the pointer to the string is held and re-used */
7119 // #define DEBUG_STRING_FREE
7120
7121#ifdef DEBUG_STRING_FREE
7122 PyObject *string_free_ls = PyList_New(0);
7123#endif
7124
7125 /* Should never happen, but it does in rare cases. */
7126 BLI_assert(self_ptr != nullptr);
7127
7128 if (self_ptr == nullptr) {
7129 PyErr_SetString(PyExc_RuntimeError,
7130 "RNA functions internal RNA pointer is null, this is a bug. aborting");
7131 return nullptr;
7132 }
7133
7134 if (self_func == nullptr) {
7135 PyErr_Format(
7136 PyExc_RuntimeError,
7137 "%.200s.<unknown>(): RNA function internal function is null, this is a bug. aborting",
7138 RNA_struct_identifier(self_ptr->type));
7139 return nullptr;
7140 }
7141
7142/* For testing. */
7143#if 0
7144 {
7145 const char *fn;
7146 int lineno;
7147 PyC_FileAndNum(&fn, &lineno);
7148 printf("pyrna_func_call > %.200s.%.200s : %.200s:%d\n",
7149 RNA_struct_identifier(self_ptr->type),
7150 RNA_function_identifier(self_func),
7151 fn,
7152 lineno);
7153 }
7154#endif
7155
7156 /* include the ID pointer for pyrna_param_to_py() so we can include the
7157 * ID pointer on return values, this only works when returned values have
7158 * the same ID as the functions. */
7159 PointerRNA funcptr = RNA_pointer_create_discrete(self_ptr->owner_id, RNA_Function, self_func);
7160
7161 const Py_ssize_t pyargs_len = PyVectorcall_NARGS(nargsf);
7162 const Py_ssize_t pykw_len = kwnames ? PyTuple_GET_SIZE(kwnames) : 0;
7163
7164 /* Temporary strings parameters point into, see #pyrna_py_to_prop.
7165 * Allocated in this functions stack frame so they out-live #RNA_function_call. */
7166 struct PyObjectLink {
7167 PyObjectLink *next;
7168 PyObject *ob;
7169 };
7170 PyObjectLink *py_coerce_ls = nullptr;
7171
7172 RNA_parameter_list_create(&parms, self_ptr, self_func);
7173 RNA_parameter_list_begin(&parms, &iter);
7174 parms_len = RNA_parameter_list_arg_count(&parms);
7175 ret_len = 0;
7176
7177 if (pyargs_len + pykw_len > parms_len) {
7179 PyErr_Format(PyExc_TypeError,
7180 "%.200s.%.200s(): takes at most %d arguments, got %d",
7181 RNA_struct_identifier(self_ptr->type),
7182 RNA_function_identifier(self_func),
7183 parms_len,
7184 pyargs_len + pykw_len);
7185 err = -1;
7186 }
7187
7188 /* Parse function parameters. */
7189 for (i = 0; iter.valid && err == 0; RNA_parameter_list_next(&iter)) {
7190 parm = iter.parm;
7191 flag_parameter = RNA_parameter_flag(parm);
7192 /* Only useful for single argument returns, we'll need another list loop for multiple. */
7193 if (flag_parameter & PARM_OUTPUT) {
7194 ret_len++;
7195 if (pret_single == nullptr) {
7196 pret_single = parm;
7197 retdata_single = iter.data;
7198 }
7199
7200 continue;
7201 }
7202
7203 item = nullptr;
7204
7205 if (i < pyargs_len) {
7206 /* New in 2.8x, optional arguments must be keywords. */
7207 if ((flag_parameter & PARM_REQUIRED) == 0) [[unlikely]] {
7208 PyErr_Format(PyExc_TypeError,
7209 "%.200s.%.200s(): required parameter \"%.200s\" to be a keyword argument!",
7210 RNA_struct_identifier(self_ptr->type),
7211 RNA_function_identifier(self_func),
7213 err = -1;
7214 break;
7215 }
7216
7217 item = args[i];
7218 kw_arg = false;
7219 }
7220 else if (kwnames != nullptr) {
7221 item = kwnames_get_item_string(args,
7222 pyargs_len,
7223 kwnames,
7224 pykw_len,
7225 RNA_property_identifier(parm)); /* Borrow reference. */
7226
7227 if (item) {
7228 kw_tot++; /* Make sure invalid keywords are not given. */
7229 }
7230
7231 kw_arg = true;
7232 }
7233
7234 if (item == nullptr) {
7235 if (flag_parameter & PARM_REQUIRED) {
7236 PyErr_Format(PyExc_TypeError,
7237 "%.200s.%.200s(): required parameter \"%.200s\" not specified",
7238 RNA_struct_identifier(self_ptr->type),
7239 RNA_function_identifier(self_func),
7241 err = -1;
7242 break;
7243 }
7244 /* PyDict_GetItemString won't raise an error. */
7245 }
7246 else {
7247
7248#ifdef DEBUG_STRING_FREE
7249 if (item) {
7250 if (PyUnicode_Check(item)) {
7251 PyList_APPEND(string_free_ls, PyUnicode_FromString(PyUnicode_AsUTF8(item)));
7252 }
7253 }
7254#endif
7255
7256 /* the error generated isn't that useful, so generate it again with a useful prefix
7257 * could also write a function to prepend to error messages */
7258 char error_prefix[512];
7259
7260 PyObject *value_coerce = nullptr;
7261 err = pyrna_py_to_prop(&funcptr, parm, iter.data, item, "", &value_coerce);
7262
7263 if (value_coerce) [[unlikely]] {
7264 PyObjectLink *link = static_cast<PyObjectLink *>(alloca(sizeof(*link)));
7265 link->next = py_coerce_ls;
7266 link->ob = value_coerce;
7267 py_coerce_ls = link;
7268 }
7269
7270 if (err != 0) {
7271 PyErr_Clear(); /* Re-raise. */
7272 pyrna_func_error_prefix(self, parm, kw_arg ? -1 : i, error_prefix, sizeof(error_prefix));
7273 pyrna_py_to_prop(&funcptr, parm, iter.data, item, error_prefix, nullptr);
7274
7275 break;
7276 }
7277 }
7278
7279 i++; /* Current argument. */
7280 }
7281
7283
7284 /* Check if we gave args that don't exist in the function
7285 * Printing the error is slow, but it should only happen when developing.
7286 * The "if" below is quick check to make sure less keyword args were passed than we gave.
7287 * (Don't overwrite the error if we have one,
7288 * otherwise can skip important messages and confuse with args).
7289 */
7290 if (err == 0 && kwnames && (pykw_len > kw_tot)) [[unlikely]] {
7291 DynStr *bad_args = BLI_dynstr_new();
7292 DynStr *good_args = BLI_dynstr_new();
7293
7294 const char *arg_name, *bad_args_str, *good_args_str;
7295 bool found = false, first = true;
7296
7297 for (Py_ssize_t i = 0; i < pykw_len; i++) {
7298 PyObject *key = PyTuple_GET_ITEM(kwnames, i); /* Borrow reference. */
7299
7300 arg_name = PyUnicode_AsUTF8(key);
7301 found = false;
7302
7303 /* Unlikely the `arg_name` is not a string, but ignore if it is. */
7304 if (arg_name == nullptr) {
7305 PyErr_Clear();
7306 }
7307 else {
7308 /* Search for arg_name. */
7309 RNA_parameter_list_begin(&parms, &iter);
7310 for (; iter.valid; RNA_parameter_list_next(&iter)) {
7311 parm = iter.parm;
7312 if (STREQ(arg_name, RNA_property_identifier(parm))) {
7313 found = true;
7314 break;
7315 }
7316 }
7317
7319
7320 if (found == false) {
7321 BLI_dynstr_appendf(bad_args, first ? "%s" : ", %s", arg_name);
7322 first = false;
7323 }
7324 }
7325 }
7326
7327 /* List good args. */
7328 first = true;
7329
7330 RNA_parameter_list_begin(&parms, &iter);
7331 for (; iter.valid; RNA_parameter_list_next(&iter)) {
7332 parm = iter.parm;
7333 if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
7334 continue;
7335 }
7336
7337 BLI_dynstr_appendf(good_args, first ? "%s" : ", %s", RNA_property_identifier(parm));
7338 first = false;
7339 }
7341
7342 bad_args_str = BLI_dynstr_get_cstring(bad_args);
7343 good_args_str = BLI_dynstr_get_cstring(good_args);
7344
7345 PyErr_Format(
7346 PyExc_TypeError,
7347 "%.200s.%.200s(): was called with invalid keyword argument(s) (%s), expected (%s)",
7348 RNA_struct_identifier(self_ptr->type),
7349 RNA_function_identifier(self_func),
7350 bad_args_str,
7351 good_args_str);
7352
7353 BLI_dynstr_free(bad_args);
7354 BLI_dynstr_free(good_args);
7355 MEM_delete(bad_args_str);
7356 MEM_delete(good_args_str);
7357
7358 err = -1;
7359 }
7360
7361 ret = nullptr;
7362 if (err == 0) {
7363 /* Call function. */
7364 ReportList reports;
7366
7367 /* No need to print any reports. We will turn errors into Python exceptions, and
7368 * Python API calls should be silent and not print info or warning messages. */
7370 RNA_function_call(C, &reports, self_ptr, self_func, &parms);
7371
7372 err = BPy_reports_to_error(&reports, PyExc_RuntimeError, true);
7373
7374 /* Return value. */
7375 if (err != -1) {
7376 if (ret_len > 0) {
7377 if (ret_len > 1) {
7378 ret = PyTuple_New(ret_len);
7379 i = 0; /* Arg index. */
7380
7381 RNA_parameter_list_begin(&parms, &iter);
7382
7383 for (; iter.valid; RNA_parameter_list_next(&iter)) {
7384 parm = iter.parm;
7385
7386 if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
7387 PyTuple_SET_ITEM(ret, i++, pyrna_param_to_py(&funcptr, parm, iter.data));
7388 }
7389 }
7390
7392 }
7393 else {
7394 ret = pyrna_param_to_py(&funcptr, pret_single, retdata_single);
7395 }
7396
7397 /* Possible there is an error in conversion. */
7398 if (ret == nullptr) {
7399 err = -1;
7400 }
7401 }
7402 }
7403 }
7404
7405#ifdef DEBUG_STRING_FREE
7406# if 0
7407 if (PyList_GET_SIZE(string_free_ls)) {
7408 printf("%.200s.%.200s(): has %d strings\n",
7409 RNA_struct_identifier(self_ptr->type),
7410 RNA_function_identifier(self_func),
7411 int(PyList_GET_SIZE(string_free_ls)));
7412 }
7413# endif
7414 Py_DECREF(string_free_ls);
7415# undef DEBUG_STRING_FREE
7416#endif
7417
7418 /* Cleanup. */
7421
7422 if (py_coerce_ls) [[unlikely]] {
7423 for (PyObjectLink *link = py_coerce_ls; link; link = link->next) {
7424 Py_DECREF(link->ob);
7425 }
7426 }
7427
7428 if (ret) {
7429 return ret;
7430 }
7431
7432 if (err == -1) {
7433 return nullptr;
7434 }
7435
7436 Py_RETURN_NONE;
7437}
7438
7439static PyObject *pyrna_func_doc_get(BPy_FunctionRNA *self, void * /*closure*/)
7440{
7441 PyObject *ret;
7442
7443 std::string args = RNA_function_as_string_keywords(nullptr, self->func, true, true, INT_MAX);
7444
7445 ret = PyUnicode_FromFormat("%.200s.%.200s(%.200s)\n%s",
7446 RNA_struct_identifier(self->ptr->type),
7448 args.c_str(),
7450
7451 return ret;
7452}
7453
7455 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
7456 /*tp_name*/ "bpy_struct_meta_idprop",
7457 /* NOTE: would be `sizeof(PyTypeObject)`,
7458 * but sub-types of Type must be #PyHeapTypeObject's. */
7459 /*tp_basicsize*/ sizeof(PyHeapTypeObject),
7460 /*tp_itemsize*/ 0,
7461 /*tp_dealloc*/ nullptr,
7462 /*tp_vectorcall_offset*/ 0,
7463 /*tp_getattr*/ nullptr,
7464 /*tp_setattr*/ nullptr,
7465 /*tp_as_async*/ nullptr,
7466 /*tp_repr*/ nullptr,
7467 /*tp_as_number*/ nullptr,
7468 /*tp_as_sequence*/ nullptr,
7469 /*tp_as_mapping*/ nullptr,
7470 /*tp_hash*/ nullptr,
7471 /*tp_call*/ nullptr,
7472 /*tp_str*/ nullptr,
7473 /*tp_getattro*/ nullptr, /* Subclassed: #pyrna_struct_meta_idprop_getattro. */
7474 /*tp_setattro*/ static_cast<setattrofunc>(pyrna_struct_meta_idprop_setattro),
7475 /*tp_as_buffer*/ nullptr,
7476 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7477 /*tp_doc*/ nullptr,
7478 /*tp_traverse*/ nullptr,
7479 /*tp_clear*/ nullptr,
7480 /*tp_richcompare*/ nullptr,
7481 /*tp_weaklistoffset*/ 0,
7482 /*tp_iter*/ nullptr,
7483 /*tp_iternext*/ nullptr,
7484 /*tp_methods*/ nullptr,
7485 /*tp_members*/ nullptr,
7486 /*tp_getset*/ nullptr,
7487#if defined(_MSC_VER)
7488 /*tp_base*/ nullptr, /* Defer assignment. */
7489#else
7490 /*tp_base*/ &PyType_Type,
7491#endif
7492 /*tp_dict*/ nullptr,
7493 /*tp_descr_get*/ nullptr,
7494 /*tp_descr_set*/ nullptr,
7495 /*tp_dictoffset*/ 0,
7496 /*tp_init*/ nullptr,
7497 /*tp_alloc*/ nullptr,
7498 /*tp_new*/ nullptr,
7499 /*tp_free*/ nullptr,
7500 /*tp_is_gc*/ nullptr,
7501 /*tp_bases*/ nullptr,
7502 /*tp_mro*/ nullptr,
7503 /*tp_cache*/ nullptr,
7504 /*tp_subclasses*/ nullptr,
7505 /*tp_weaklist*/ nullptr,
7506 /*tp_del*/ nullptr,
7507 /*tp_version_tag*/ 0,
7508 /*tp_finalize*/ nullptr,
7509 /*tp_vectorcall*/ nullptr,
7510};
7511
7512/*-----------------------BPy_StructRNA method def------------------------------*/
7513
7514/* -------------------------------------------------------------------- */
7541
7542static PyObject *pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject * /*kwds*/);
7543static int pyrna_struct_init(PyObject *self, PyObject *args, PyObject * /*kwds*/);
7544static void pyrna_struct_dealloc(PyObject *self);
7545
7546PyTypeObject pyrna_struct_Type = {
7547 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
7548 /*tp_name*/ "bpy_struct",
7549 /*tp_basicsize*/ sizeof(BPy_StructRNA),
7550 /*tp_itemsize*/ 0,
7551 /*tp_dealloc*/ pyrna_struct_dealloc,
7552 /*tp_vectorcall_offset*/ 0,
7553 /*tp_getattr*/ nullptr,
7554 /*tp_setattr*/ nullptr,
7555 /*tp_as_async*/ nullptr,
7556 /*tp_repr*/ reinterpret_cast<reprfunc>(pyrna_struct_repr),
7557 /*tp_as_number*/ nullptr,
7558 /*tp_as_sequence*/ &pyrna_struct_as_sequence,
7559 /*tp_as_mapping*/ &pyrna_struct_as_mapping,
7560 /*tp_hash*/ reinterpret_cast<hashfunc>(pyrna_struct_hash),
7561 /*tp_call*/ nullptr,
7562 /*tp_str*/ reinterpret_cast<reprfunc>(pyrna_struct_str),
7563 /*tp_getattro*/ reinterpret_cast<getattrofunc>(pyrna_struct_getattro),
7564 /*tp_setattro*/ reinterpret_cast<setattrofunc>(pyrna_struct_setattro),
7565 /*tp_as_buffer*/ nullptr,
7566 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
7567#ifdef USE_PYRNA_STRUCT_REFERENCE
7568 | Py_TPFLAGS_HAVE_GC
7569#endif
7570 ,
7571 /*tp_doc*/ nullptr,
7572#ifdef USE_PYRNA_STRUCT_REFERENCE
7573 /*tp_traverse*/ (traverseproc)pyrna_struct_traverse,
7574 /*tp_clear*/ (inquiry)pyrna_struct_clear,
7575#else
7576 /*tp_traverse*/ nullptr,
7577 /*tp_clear*/ nullptr,
7578#endif /* !USE_PYRNA_STRUCT_REFERENCE */
7579 /*tp_richcompare*/ static_cast<richcmpfunc>(pyrna_struct_richcmp),
7580#ifdef USE_WEAKREFS
7581 /*tp_weaklistoffset*/ offsetof(BPy_StructRNA, in_weakreflist),
7582#else
7583 0,
7584#endif
7585 /*tp_iter*/ nullptr,
7586 /*tp_iternext*/ nullptr,
7587 /*tp_methods*/ pyrna_struct_methods,
7588 /*tp_members*/ nullptr,
7589 /*tp_getset*/ pyrna_struct_getseters,
7590 /*tp_base*/ nullptr,
7591 /*tp_dict*/ nullptr,
7592 /*tp_descr_get*/ nullptr,
7593 /*tp_descr_set*/ nullptr,
7594 /*tp_dictoffset*/ 0,
7595 /*tp_init*/ pyrna_struct_init,
7596 /*tp_alloc*/ nullptr,
7597 /*tp_new*/ pyrna_struct_new,
7598 /*tp_free*/ nullptr,
7599 /*tp_is_gc*/ nullptr,
7600 /*tp_bases*/ nullptr,
7601 /*tp_mro*/ nullptr,
7602 /*tp_cache*/ nullptr,
7603 /*tp_subclasses*/ nullptr,
7604 /*tp_weaklist*/ nullptr,
7605 /*tp_del*/ nullptr,
7606 /*tp_version_tag*/ 0,
7607 /*tp_finalize*/ nullptr,
7608 /*tp_vectorcall*/ nullptr,
7609};
7610
7611static PyObject *pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject * /*kwds*/)
7612{
7613 if (PyTuple_GET_SIZE(args) != 1) {
7614 PyErr_Format(PyExc_TypeError, "bpy_struct.__new__(struct): expected a single argument");
7615 return nullptr;
7616 }
7617
7618 PyObject *arg_1 = PyTuple_GET_ITEM(args, 0);
7619
7620 /* Ignore the special 'PyCapsule' argument used only by internal bpy_rna code. */
7621 if (!PyCapsule_CheckExact(arg_1)) {
7622 BPy_StructRNA *base = reinterpret_cast<BPy_StructRNA *>(arg_1);
7623 /* Error, invalid type given. */
7624 if (!PyType_IsSubtype(Py_TYPE(base), &pyrna_struct_Type)) {
7625 PyErr_Format(
7626 PyExc_TypeError,
7627 "bpy_struct.__new__(struct): struct type '%.200s' is not a subtype of bpy_struct",
7628 Py_TYPE(base)->tp_name);
7629 return nullptr;
7630 }
7631 /* Same type, simply use the given data. */
7632 if (Py_TYPE(base) == type) {
7633 BLI_assert(base->ptr.has_value());
7634 Py_INCREF(base);
7635 return reinterpret_cast<PyObject *>(base);
7636 }
7637 /* NOTE: Further copy of the 'base' content into the new object will happen in
7638 * #pyrna_struct_init. */
7639 }
7640
7641 /* Only allocate the #PyObject data, do not construct/initialize anything else. */
7642 PyObject *self = type->tp_alloc(type, 0);
7643 BPy_StructRNA *self_struct = reinterpret_cast<BPy_StructRNA *>(self);
7644 if (self) {
7645#ifdef USE_PYRNA_STRUCT_REFERENCE
7646 /* #PyType_GenericAlloc will have set tracking.
7647 * We only want tracking when `StructRNA.reference` has been set. */
7648 PyObject_GC_UnTrack(self);
7649#endif
7650 self_struct->ptr = std::nullopt;
7651 }
7652 /* Pass on exception & nullptr if tp_alloc fails. */
7653 return self;
7654}
7655
7656static int pyrna_struct_init(PyObject *self, PyObject *args, PyObject * /*kwds*/)
7657{
7658 BPy_StructRNA *self_struct = reinterpret_cast<BPy_StructRNA *>(self);
7659
7660 size_t args_num = PyTuple_GET_SIZE(args);
7661 if (args_num != 1) {
7662 PyErr_Format(PyExc_TypeError, "bpy_struct.__init__(self, struct): expected a single argument");
7663 return -1;
7664 }
7665
7666 PyObject *arg_1 = PyTuple_GET_ITEM(args, 0);
7667 const PointerRNA *ptr = nullptr;
7668 if (PyCapsule_CheckExact(arg_1)) {
7669 /* `bpy_rna` internal code will call object creation with a PyCapsule argument wrapping up a
7670 * PointerRNA pointer. */
7671 ptr = static_cast<PointerRNA *>(
7672 PyCapsule_GetPointer(arg_1, BPy_capsule_PointerRNA_identifier));
7673 }
7674 else {
7675 BPy_StructRNA *base_struct = reinterpret_cast<BPy_StructRNA *>(arg_1);
7676
7677 /* Error, invalid type given. */
7678 if (!PyType_IsSubtype(Py_TYPE(base_struct), &pyrna_struct_Type)) {
7679 PyErr_Format(PyExc_TypeError,
7680 "bpy_struct.__init__(self, struct): struct type '%.200s' is not a subtype of "
7681 "bpy_struct",
7682 Py_TYPE(base_struct)->tp_name);
7683 return -1;
7684 }
7685 /* Same object as the 'base' argument (see #pyrna_struct_new), nothing to do . */
7686 if (base_struct == self_struct) {
7687 BLI_assert(self_struct->ptr.has_value());
7688 return 0;
7689 }
7690
7691 /* Else, use data from the base to initialize this object. */
7692 ptr = &base_struct->ptr.value();
7693 }
7694
7695 if (ptr == nullptr) {
7696 PyErr_Format(PyExc_TypeError,
7697 "bpy_struct.__init__(self, struct): failed to get a valid PointerRNA data "
7698 "from the given `struct` argument");
7699 return -1;
7700 }
7701
7702 self_struct->ptr.reset();
7703 self_struct->ptr = *ptr;
7704
7705 return 0;
7706}
7707
7708/* Own dealloc so that the PointerRNA can be destructed, and the IDProperty storage can be freed if
7709 * needed.
7710 *
7711 * Note: This should rather be in `tp_finalize` (aka `__del__`), but static types default dealloc
7712 * never calls this. */
7713static void pyrna_struct_dealloc(PyObject *self)
7714{
7715 /* Save the current exception, if any. */
7716 PyObject *error_type, *error_value, *error_traceback;
7717 PyErr_Fetch(&error_type, &error_value, &error_traceback);
7718
7719 BPy_StructRNA *self_struct = reinterpret_cast<BPy_StructRNA *>(self);
7720
7721#ifdef PYRNA_FREE_SUPPORT
7722 if (self_struct->freeptr && *self_struct->ptr) {
7723 IDP_FreeProperty(self_struct->ptr->data);
7724 self_struct->ptr->data = nullptr;
7725 }
7726#endif /* PYRNA_FREE_SUPPORT */
7727
7728#ifdef USE_WEAKREFS
7729 if (self_struct->in_weakreflist != nullptr) {
7730 PyObject_ClearWeakRefs(self);
7731 }
7732#endif
7733
7734#ifdef USE_PYRNA_STRUCT_REFERENCE
7735 if (self_struct->reference) {
7736 PyObject_GC_UnTrack(self);
7737 pyrna_struct_clear(self_struct);
7738 }
7739 else {
7740 PyTypeObject *base = Py_TYPE(self)->tp_base;
7741 /* Python temporarily tracks these types when freeing, see Python bug 26617. */
7742 if (base && PyType_IS_GC(base)) {
7743 PyObject_GC_UnTrack(self);
7744 }
7745 BLI_assert(!PyObject_GC_IsTracked(self));
7746 }
7747#endif /* !USE_PYRNA_STRUCT_REFERENCE */
7748
7749 self_struct->ptr.~optional();
7750
7751 Py_TYPE(self)->tp_free(self);
7752
7753 /* Restore the saved exception. */
7754 PyErr_Restore(error_type, error_value, error_traceback);
7755}
7756
7758
7759/*-----------------------BPy_PropertyRNA method def------------------------------*/
7760
7761/* -------------------------------------------------------------------- */
7779
7780static PyObject *pyrna_property_new(PyTypeObject *type, PyObject *args, PyObject * /*kwds*/);
7781static int pyrna_property_init(PyObject *self, PyObject *args, PyObject * /*kwds*/);
7782static void pyrna_property_dealloc(PyObject *self);
7783static int pyrna_property_array_init(PyObject *self, PyObject *args, PyObject * /*kwds*/);
7784
7785PyTypeObject pyrna_prop_Type = {
7786 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
7787 /*tp_name*/ "bpy_prop",
7788 /*tp_basicsize*/ sizeof(BPy_PropertyRNA),
7789 /*tp_itemsize*/ 0,
7790 /*tp_dealloc*/ pyrna_property_dealloc,
7791 /*tp_vectorcall_offset*/ 0,
7792 /*tp_getattr*/ nullptr,
7793 /*tp_setattr*/ nullptr,
7794 /*tp_as_async*/ nullptr,
7795 /*tp_repr*/ reinterpret_cast<reprfunc>(pyrna_prop_repr),
7796 /*tp_as_number*/ nullptr,
7797 /*tp_as_sequence*/ nullptr,
7798 /*tp_as_mapping*/ nullptr,
7799 /*tp_hash*/ reinterpret_cast<hashfunc>(pyrna_prop_hash),
7800 /*tp_call*/ nullptr,
7801 /*tp_str*/ reinterpret_cast<reprfunc>(pyrna_prop_str),
7802 /*tp_getattro*/ nullptr,
7803 /*tp_setattro*/ nullptr,
7804 /*tp_as_buffer*/ nullptr,
7805 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7806 /*tp_doc*/ nullptr,
7807 /*tp_traverse*/ nullptr,
7808 /*tp_clear*/ nullptr,
7809 /*tp_richcompare*/ static_cast<richcmpfunc>(pyrna_prop_richcmp),
7810#ifdef USE_WEAKREFS
7811 /*tp_weaklistoffset*/ offsetof(BPy_PropertyRNA, in_weakreflist),
7812#else
7813 /*tp_weaklistoffset*/ 0,
7814#endif
7815 /*tp_iter*/ nullptr,
7816 /*tp_iternext*/ nullptr,
7817 /*tp_methods*/ pyrna_prop_methods,
7818 /*tp_members*/ nullptr,
7819 /*tp_getset*/ pyrna_prop_getseters,
7820 /*tp_base*/ nullptr,
7821 /*tp_dict*/ nullptr,
7822 /*tp_descr_get*/ nullptr,
7823 /*tp_descr_set*/ nullptr,
7824 /*tp_dictoffset*/ 0,
7825 /*tp_init*/ pyrna_property_init,
7826 /*tp_alloc*/ nullptr,
7827 /*tp_new*/ pyrna_property_new,
7828 /*tp_free*/ nullptr,
7829 /*tp_is_gc*/ nullptr,
7830 /*tp_bases*/ nullptr,
7831 /*tp_mro*/ nullptr,
7832 /*tp_cache*/ nullptr,
7833 /*tp_subclasses*/ nullptr,
7834 /*tp_weaklist*/ nullptr,
7835 /*tp_del*/ nullptr,
7836 /*tp_version_tag*/ 0,
7837 /*tp_finalize*/ nullptr,
7838 /*tp_vectorcall*/ nullptr,
7839};
7840
7842 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
7843 /*tp_name*/ "bpy_prop_array",
7844 /*tp_basicsize*/ sizeof(BPy_PropertyArrayRNA),
7845 /*tp_itemsize*/ 0,
7846 /*tp_dealloc*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7847 /*tp_vectorcall_offset*/ 0,
7848 /*tp_getattr*/ nullptr,
7849 /*tp_setattr*/ nullptr,
7850 /*tp_as_async*/ nullptr,
7851 /*tp_repr*/ reinterpret_cast<reprfunc>(pyrna_prop_array_repr),
7852 /*tp_as_number*/ &pyrna_prop_array_as_number,
7853 /*tp_as_sequence*/ &pyrna_prop_array_as_sequence,
7854 /*tp_as_mapping*/ &pyrna_prop_array_as_mapping,
7855 /*tp_hash*/ nullptr,
7856 /*tp_call*/ nullptr,
7857 /*tp_str*/ nullptr,
7858 /*tp_getattro*/ reinterpret_cast<getattrofunc>(pyrna_prop_array_getattro),
7859 /*tp_setattro*/ nullptr,
7860 /*tp_as_buffer*/ nullptr,
7861 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7862 /*tp_doc*/ nullptr,
7863 /*tp_traverse*/ nullptr,
7864 /*tp_clear*/ nullptr,
7865 /*tp_richcompare*/ nullptr,
7866#ifdef USE_WEAKREFS
7867 /*tp_weaklistoffset*/ offsetof(BPy_PropertyArrayRNA, in_weakreflist),
7868#else
7869 /*tp_weaklistoffset*/ 0,
7870#endif
7871 /*tp_iter*/ reinterpret_cast<getiterfunc>(pyrna_prop_array_iter),
7872 /*tp_iternext*/ nullptr,
7873 /*tp_methods*/ pyrna_prop_array_methods,
7874 /*tp_members*/ nullptr,
7875 /*tp_getset*/ nullptr /* Subclassed: #pyrna_prop_getseters. */,
7876 /*tp_base*/ &pyrna_prop_Type,
7877 /*tp_dict*/ nullptr,
7878 /*tp_descr_get*/ nullptr,
7879 /*tp_descr_set*/ nullptr,
7880 /*tp_dictoffset*/ 0,
7881 /*tp_init*/ pyrna_property_array_init,
7882 /*tp_alloc*/ nullptr,
7883 /*tp_new*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7884 /*tp_free*/ nullptr,
7885 /*tp_is_gc*/ nullptr,
7886 /*tp_bases*/ nullptr,
7887 /*tp_mro*/ nullptr,
7888 /*tp_cache*/ nullptr,
7889 /*tp_subclasses*/ nullptr,
7890 /*tp_weaklist*/ nullptr,
7891 /*tp_del*/ nullptr,
7892 /*tp_version_tag*/ 0,
7893 /*tp_finalize*/ nullptr,
7894 /*tp_vectorcall*/ nullptr,
7895};
7896
7898 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
7899 /*tp_name*/ "bpy_prop_collection",
7900 /*tp_basicsize*/ sizeof(BPy_PropertyRNA),
7901 /*tp_itemsize*/ 0,
7902 /*tp_dealloc*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7903 /*tp_vectorcall_offset*/ 0,
7904 /*tp_getattr*/ nullptr,
7905 /*tp_setattr*/ nullptr,
7906 /*tp_as_async*/ nullptr,
7907 /*tp_repr*/ nullptr, /* Subclassed, no need to define. */
7908 /*tp_as_number*/ &pyrna_prop_collection_as_number,
7909 /*tp_as_sequence*/ &pyrna_prop_collection_as_sequence,
7910 /*tp_as_mapping*/ &pyrna_prop_collection_as_mapping,
7911 /*tp_hash*/ nullptr,
7912 /*tp_call*/ nullptr,
7913 /*tp_str*/ nullptr,
7914 /*tp_getattro*/ reinterpret_cast<getattrofunc>(pyrna_prop_collection_getattro),
7915 /*tp_setattro*/ reinterpret_cast<setattrofunc>(pyrna_prop_collection_setattro),
7916 /*tp_as_buffer*/ nullptr,
7917 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7918 /*tp_doc*/ nullptr,
7919 /*tp_traverse*/ nullptr,
7920 /*tp_clear*/ nullptr,
7921 /*tp_richcompare*/ nullptr,
7922#ifdef USE_WEAKREFS
7923 /*tp_weaklistoffset*/ offsetof(BPy_PropertyRNA, in_weakreflist),
7924#else
7925 /*tp_weaklistoffset*/ 0,
7926#endif
7927 /*tp_iter*/ static_cast<getiterfunc>(pyrna_prop_collection_iter),
7928 /*tp_iternext*/ nullptr,
7929 /*tp_methods*/ pyrna_prop_collection_methods,
7930 /*tp_members*/ nullptr,
7931 /*tp_getset*/ nullptr /* Subclassed: see #pyrna_prop_getseters. */,
7932 /*tp_base*/ &pyrna_prop_Type,
7933 /*tp_dict*/ nullptr,
7934 /*tp_descr_get*/ nullptr,
7935 /*tp_descr_set*/ nullptr,
7936 /*tp_dictoffset*/ 0,
7937 /*tp_init*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7938 /*tp_alloc*/ nullptr,
7939 /*tp_new*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7940 /*tp_free*/ nullptr,
7941 /*tp_is_gc*/ nullptr,
7942 /*tp_bases*/ nullptr,
7943 /*tp_mro*/ nullptr,
7944 /*tp_cache*/ nullptr,
7945 /*tp_subclasses*/ nullptr,
7946 /*tp_weaklist*/ nullptr,
7947 /*tp_del*/ nullptr,
7948 /*tp_version_tag*/ 0,
7949 /*tp_finalize*/ nullptr,
7950 /*tp_vectorcall*/ nullptr,
7951};
7952
7953/* only for add/remove/move methods */
7955 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
7956 /*tp_name*/ "bpy_prop_collection_idprop",
7957 /*tp_basicsize*/ sizeof(BPy_PropertyRNA),
7958 /*tp_itemsize*/ 0,
7959 /*tp_dealloc*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7960 /*tp_vectorcall_offset*/ 0,
7961 /*tp_getattr*/ nullptr,
7962 /*tp_setattr*/ nullptr,
7963 /*tp_compare*/ nullptr, /* DEPRECATED. */
7964 /*tp_repr*/ nullptr, /* Subclassed, no need to define. */
7965 /*tp_as_number*/ nullptr,
7966 /*tp_as_sequence*/ nullptr,
7967 /*tp_as_mapping*/ nullptr,
7968 /*tp_hash*/ nullptr,
7969 /*tp_call*/ nullptr,
7970 /*tp_str*/ nullptr,
7971 /*tp_getattro*/ nullptr,
7972 /*tp_setattro*/ nullptr,
7973 /*tp_as_buffer*/ nullptr,
7974 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
7975 /*tp_doc*/ nullptr,
7976 /*tp_traverse*/ nullptr,
7977 /*tp_clear*/ nullptr,
7978 /*tp_richcompare*/ nullptr,
7979#ifdef USE_WEAKREFS
7980 /*tp_weaklistoffset*/ offsetof(BPy_PropertyRNA, in_weakreflist),
7981#else
7982 /*tp_weaklistoffset*/ 0,
7983#endif
7984 /*tp_iter*/ nullptr,
7985 /*tp_iternext*/ nullptr,
7987 /*tp_members*/ nullptr,
7988 /*tp_getset*/ nullptr /* Subclassed: #pyrna_prop_getseters. */,
7989 /*tp_base*/ &pyrna_prop_collection_Type,
7990 /*tp_dict*/ nullptr,
7991 /*tp_descr_get*/ nullptr,
7992 /*tp_descr_set*/ nullptr,
7993 /*tp_dictoffset*/ 0,
7994 /*tp_init*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7995 /*tp_alloc*/ nullptr,
7996 /*tp_new*/ nullptr, /* Inherited from #pyrna_prop_Type. */
7997 /*tp_free*/ nullptr,
7998 /*tp_is_gc*/ nullptr,
7999 /*tp_bases*/ nullptr,
8000 /*tp_mro*/ nullptr,
8001 /*tp_cache*/ nullptr,
8002 /*tp_subclasses*/ nullptr,
8003 /*tp_weaklist*/ nullptr,
8004 /*tp_del*/ nullptr,
8005 /*tp_version_tag*/ 0,
8006 /*tp_finalize*/ nullptr,
8007 /*tp_vectorcall*/ nullptr,
8008};
8009
8010static PyObject *pyrna_property_new(PyTypeObject *type, PyObject *args, PyObject * /*kwds*/)
8011{
8012 if (PyTuple_GET_SIZE(args) != 1) {
8013 PyErr_Format(PyExc_TypeError, "bpy_prop.__new__(property): expected a single argument");
8014 return nullptr;
8015 }
8016
8017 PyObject *arg_1 = PyTuple_GET_ITEM(args, 0);
8018
8019 /* Ignore the special 'PyCapsule' argument used only by internal bpy_rna code. */
8020 if (!PyCapsule_CheckExact(arg_1)) {
8021 BPy_PropertyRNA *base = reinterpret_cast<BPy_PropertyRNA *>(arg_1);
8022 /* Error, invalid type given. */
8023 if (!PyType_IsSubtype(Py_TYPE(base), &pyrna_prop_Type)) {
8024 PyErr_Format(
8025 PyExc_TypeError,
8026 "bpy_prop.__new__(property): property type '%.200s' is not a subtype of bpy_prop",
8027 Py_TYPE(base)->tp_name);
8028 return nullptr;
8029 }
8030 /* Same type, simply use the given data. */
8031 if (Py_TYPE(base) == type) {
8032 BLI_assert(base->ptr.has_value());
8033 Py_INCREF(base);
8034 return reinterpret_cast<PyObject *>(base);
8035 }
8036 /* NOTE: Further copy of the 'base' content into the new object will happen in
8037 * #pyrna_property_init. */
8038 }
8039
8040 /* Only allocate the #PyObject data, do not construct/initialize anything else. */
8041 PyObject *self = type->tp_alloc(type, 0);
8042 BPy_PropertyRNA *self_property = reinterpret_cast<BPy_PropertyRNA *>(self);
8043 if (self) {
8044 self_property->ptr = std::nullopt;
8045 }
8046 /* Pass on exception & nullptr if tp_alloc fails. */
8047 return self;
8048}
8049
8050static int pyrna_property_init(PyObject *self, PyObject *args, PyObject * /*kwds*/)
8051{
8052 BPy_PropertyRNA *self_property = reinterpret_cast<BPy_PropertyRNA *>(self);
8053
8054 size_t args_num = PyTuple_GET_SIZE(args);
8055 if (args_num != 1) {
8056 PyErr_Format(PyExc_TypeError, "bpy_prop.__init__(self, property): expected a single argument");
8057 return -1;
8058 }
8059
8060 PyObject *arg_1 = PyTuple_GET_ITEM(args, 0);
8061 const PointerRNA *ptr = nullptr;
8062 PropertyRNA *prop = nullptr;
8063 if (PyCapsule_CheckExact(arg_1)) {
8064 /* `bpy_rna` internal code will call object creation with a PyCapsule argument wrapping up a
8065 * PointerRNA and PropertyRNA pointers. */
8066 BPy_PropertyPointerRNA_Reference *pypropptr_rna =
8067 static_cast<BPy_PropertyPointerRNA_Reference *>(
8068 PyCapsule_GetPointer(arg_1, BPy_PropertyPointerRNA_capsule_identifier));
8069 if (pypropptr_rna) {
8070 ptr = pypropptr_rna->ptr;
8071 prop = pypropptr_rna->prop;
8072 }
8073 }
8074 else {
8075 BPy_PropertyRNA *base_property = reinterpret_cast<BPy_PropertyRNA *>(arg_1);
8076
8077 /* Error, invalid type given. */
8078 if (!PyType_IsSubtype(Py_TYPE(base_property), &pyrna_prop_Type)) {
8079 PyErr_Format(
8080 PyExc_TypeError,
8081 "bpy_prop.__init__(self, property): property type '%.200s' is not a subtype of bpy_prop",
8082 Py_TYPE(base_property)->tp_name);
8083 return -1;
8084 }
8085 /* Same object as the 'base' argument (see #pyrna_property_new), nothing to do . */
8086 if (base_property == self_property) {
8087 BLI_assert(self_property->ptr.has_value());
8088 return 0;
8089 }
8090 ptr = &base_property->ptr.value();
8091 prop = base_property->prop;
8092 }
8093
8094 self_property->ptr = *ptr;
8095 self_property->prop = prop;
8096
8097 return 0;
8098}
8099
8100static void pyrna_property_dealloc(PyObject *self)
8101{
8102 /* Save the current exception, if any. */
8103 PyObject *error_type, *error_value, *error_traceback;
8104 PyErr_Fetch(&error_type, &error_value, &error_traceback);
8105
8106 BPy_PropertyRNA *self_property = reinterpret_cast<BPy_PropertyRNA *>(self);
8107#ifdef USE_WEAKREFS
8108 if (self_property->in_weakreflist != nullptr) {
8109 PyObject_ClearWeakRefs(self);
8110 }
8111#endif
8112
8113 self_property->ptr.~optional();
8114
8115 Py_TYPE(self)->tp_free(self);
8116
8117 /* Restore the saved exception. */
8118 PyErr_Restore(error_type, error_value, error_traceback);
8119}
8120
8121static int pyrna_property_array_init(PyObject *self, PyObject *args, PyObject * /*kwds*/)
8122{
8123 BPy_PropertyArrayRNA *self_property = reinterpret_cast<BPy_PropertyArrayRNA *>(self);
8124
8125 size_t args_num = PyTuple_GET_SIZE(args);
8126 if (args_num != 1) {
8127 PyErr_Format(PyExc_TypeError,
8128 "bpy_prop_array.__init__(self, property): expected a single argument");
8129 return -1;
8130 }
8131
8132 PyObject *arg_1 = PyTuple_GET_ITEM(args, 0);
8133 const PointerRNA *ptr = nullptr;
8134 PropertyRNA *prop = nullptr;
8135 if (PyCapsule_CheckExact(arg_1)) {
8136 /* `bpy_rna` internal code will call object creation with a PyCapsule argument wrapping up a
8137 * PointerRNA and PropertyRNA pointers. */
8138 BPy_PropertyPointerRNA_Reference *pypropptr_rna =
8139 static_cast<BPy_PropertyPointerRNA_Reference *>(
8140 PyCapsule_GetPointer(arg_1, BPy_PropertyPointerRNA_capsule_identifier));
8141 if (pypropptr_rna) {
8142 ptr = pypropptr_rna->ptr;
8143 prop = pypropptr_rna->prop;
8144 }
8145 }
8146 else {
8147 BPy_PropertyArrayRNA *base_property = reinterpret_cast<BPy_PropertyArrayRNA *>(arg_1);
8148
8149 /* Error, invalid type given. */
8150 if (!PyType_IsSubtype(Py_TYPE(base_property), &pyrna_prop_array_Type)) {
8151 PyErr_Format(PyExc_TypeError,
8152 "bpy_prop_array.__init__(self, property): property type '%.200s' is not a "
8153 "subtype of bpy_prop_array",
8154 Py_TYPE(base_property)->tp_name);
8155 return -1;
8156 }
8157 /* Same object as the 'base' argument (see #pyrna_property_new), nothing to do . */
8158 if (base_property == self_property) {
8159 BLI_assert(self_property->ptr.has_value());
8160 return 0;
8161 }
8162 ptr = &base_property->ptr.value();
8163 prop = base_property->prop;
8164 }
8165
8166 self_property->prop = prop;
8167 self_property->arraydim = 0;
8168 self_property->arrayoffset = 0;
8169 self_property->ptr = *ptr;
8170
8171 return 0;
8172}
8173
8174#ifdef USE_PYRNA_ITER
8175/* --- collection iterator: start --- */
8176/* Wrap RNA collection iterator functions. */
8177/*
8178 * RNA_property_collection_begin(...)
8179 * RNA_property_collection_next(...)
8180 * RNA_property_collection_end(...)
8181 */
8182
8183static PyObject *pyrna_prop_collection_iter_new(PyTypeObject *type,
8184 PyObject * /*args*/,
8185 PyObject * /*kwds*/);
8186static int pyrna_prop_collection_iter_init(PyObject *self,
8187 PyObject * /*args*/,
8188 PyObject * /*kwds*/);
8189static void pyrna_prop_collection_iter_dealloc(PyObject *self);
8190static PyObject *pyrna_prop_collection_iter_next(PyObject *self);
8191
8192static PyTypeObject pyrna_prop_collection_iter_Type = {
8193 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
8194 /*tp_name*/ "bpy_prop_collection_iter",
8195 /*tp_basicsize*/ sizeof(BPy_PropertyCollectionIterRNA),
8196 /*tp_itemsize*/ 0,
8198 /*tp_vectorcall_offset*/ 0,
8199 /*tp_getattr*/ nullptr,
8200 /*tp_setattr*/ nullptr,
8201 /*tp_as_async*/ nullptr,
8202 /*tp_repr*/ nullptr, /* No need to define, sub-classed. */
8203 /*tp_as_number*/ nullptr,
8204 /*tp_as_sequence*/ nullptr,
8205 /*tp_as_mapping*/ nullptr,
8206 /*tp_hash*/ nullptr,
8207 /*tp_call*/ nullptr,
8208 /*tp_str*/ nullptr,
8209 /*tp_getattro*/ PyObject_GenericGetAttr,
8210 /*tp_setattro*/ nullptr,
8211 /*tp_as_buffer*/ nullptr,
8212 /*tp_flags*/ Py_TPFLAGS_DEFAULT,
8213 /*tp_doc*/ nullptr,
8214 /*tp_traverse*/ nullptr,
8215 /*tp_clear*/ nullptr,
8216 /*tp_richcompare*/ nullptr,
8217# ifdef USE_WEAKREFS
8218 /*tp_weaklistoffset*/ offsetof(BPy_PropertyCollectionIterRNA, in_weakreflist),
8219# else
8220 /*tp_weaklistoffset*/ 0,
8221# endif
8222 /*tp_iter*/ PyObject_SelfIter,
8223 /*tp_iternext*/ pyrna_prop_collection_iter_next,
8224 /*tp_methods*/ nullptr,
8225 /*tp_members*/ nullptr,
8226 /*tp_getset*/ nullptr,
8227 /*tp_base*/ nullptr,
8228 /*tp_dict*/ nullptr,
8229 /*tp_descr_get*/ nullptr,
8230 /*tp_descr_set*/ nullptr,
8231 /*tp_dictoffset*/ 0,
8233 /*tp_alloc*/ nullptr,
8235 /*tp_free*/ nullptr,
8236 /*tp_is_gc*/ nullptr,
8237 /*tp_bases*/ nullptr,
8238 /*tp_mro*/ nullptr,
8239 /*tp_cache*/ nullptr,
8240 /*tp_subclasses*/ nullptr,
8241 /*tp_weaklist*/ nullptr,
8242 /*tp_del*/ nullptr,
8243 /*tp_version_tag*/ 0,
8244 /*tp_finalize*/ nullptr,
8245 /*tp_vectorcall*/ nullptr,
8246};
8247
8248static PyObject *pyrna_prop_collection_iter_new(PyTypeObject *type,
8249 PyObject *args,
8250 PyObject * /*kwds*/)
8251{
8252 if (PyTuple_GET_SIZE(args) != 1) {
8253 PyErr_Format(PyExc_TypeError,
8254 "bpy_prop_collection_iter.__new__(arg): expected a single argument");
8255 return nullptr;
8256 }
8257
8258 PyObject *arg_1 = PyTuple_GET_ITEM(args, 0);
8259 /* Only accept the special 'PyCapsule' argument used by internal bpy_rna code. */
8260 if (!PyCapsule_CheckExact(arg_1)) {
8261 PyErr_Format(PyExc_TypeError,
8262 "bpy_prop_collection_iter.__new__(arg): arg type '%.200s' is not a PyCapsule",
8263 Py_TYPE(arg_1)->tp_name);
8264 return nullptr;
8265 }
8266
8267 /* Only allocate the #PyObject data, do not construct/initialize anything else. */
8268 PyObject *self = type->tp_alloc(type, 0);
8269 BPy_PropertyCollectionIterRNA *self_prop_iter =
8270 reinterpret_cast<BPy_PropertyCollectionIterRNA *>(self);
8271 if (self_prop_iter) {
8272 self_prop_iter->iter = std::nullopt;
8273 }
8274
8275 return self;
8276}
8277
8278static int pyrna_prop_collection_iter_init(PyObject *self, PyObject *args, PyObject * /*kwds*/)
8279{
8280 BPy_PropertyCollectionIterRNA *self_prop_iter =
8281 reinterpret_cast<BPy_PropertyCollectionIterRNA *>(self);
8282
8283 size_t args_num = PyTuple_GET_SIZE(args);
8284 if (args_num != 1) {
8285 PyErr_Format(
8286 PyExc_TypeError,
8287 "bpy_prop_collection_iter.__init__(self, arg): expected at most a single argument");
8288 return -1;
8289 }
8290
8291 PyObject *arg_1 = PyTuple_GET_ITEM(args, 0);
8292 const PointerRNA *ptr = nullptr;
8293 PropertyRNA *prop = nullptr;
8294 if (PyCapsule_CheckExact(arg_1)) {
8295 /* `bpy_rna` internal code will call object creation with a PyCapsule argument wrapping up a
8296 * PointerRNA and PropertyRNA pointers. */
8297 BPy_PropertyPointerRNA_Reference *pypropptr_rna =
8298 static_cast<BPy_PropertyPointerRNA_Reference *>(
8299 PyCapsule_GetPointer(arg_1, BPy_PropertyPointerRNA_capsule_identifier));
8300 if (pypropptr_rna) {
8301 ptr = pypropptr_rna->ptr;
8302 prop = pypropptr_rna->prop;
8303 }
8304 }
8305 else {
8306 PyErr_Format(
8307 PyExc_TypeError,
8308 "bpy_prop_collection_iter.__init__(self, arg): arg type '%.200s' is not a PyCapsule",
8309 Py_TYPE(arg_1)->tp_name);
8310 }
8311
8312 if (self_prop_iter->iter.has_value()) {
8313 RNA_property_collection_end(&self_prop_iter->iter.value());
8314 self_prop_iter->iter.reset();
8315 }
8316 self_prop_iter->iter = CollectionPropertyIterator();
8318 const_cast<PointerRNA *>(ptr), prop, &self_prop_iter->iter.value());
8319
8320 return 0;
8321}
8322
8323static void pyrna_prop_collection_iter_dealloc(PyObject *self)
8324{
8325 /* Save the current exception, if any. */
8326 PyObject *error_type, *error_value, *error_traceback;
8327 PyErr_Fetch(&error_type, &error_value, &error_traceback);
8328
8329 BPy_PropertyCollectionIterRNA *self_property = reinterpret_cast<BPy_PropertyCollectionIterRNA *>(
8330 self);
8331# ifdef USE_WEAKREFS
8332 if (self_property->in_weakreflist != nullptr) {
8333 PyObject_ClearWeakRefs(self);
8334 }
8335# endif
8336
8337 if (self_property->iter.has_value()) {
8338 RNA_property_collection_end(&self_property->iter.value());
8339 self_property->iter.reset();
8340 }
8341
8342 Py_TYPE(self)->tp_free(self);
8343
8344 /* Restore the saved exception. */
8345 PyErr_Restore(error_type, error_value, error_traceback);
8346}
8347
8349{
8350 /* Pass the PointerRNA and PropertyRNA to `__new__`/`__init__` functions as an opaque PyCapsule
8351 * object. */
8352 BPy_PropertyPointerRNA_Reference prop_ptr{ptr, prop};
8353 PyObject *pypropptr_rna = PyCapsule_New(
8354 &prop_ptr, BPy_PropertyPointerRNA_capsule_identifier, nullptr);
8355
8356 PyObject *self = PyObject_CallOneArg(
8357 reinterpret_cast<PyObject *>(&pyrna_prop_collection_iter_Type), pypropptr_rna);
8358 BPy_PropertyCollectionIterRNA *self_property = reinterpret_cast<BPy_PropertyCollectionIterRNA *>(
8359 self);
8360
8361 BLI_assert(self_property->iter.has_value());
8362 Py_DECREF(pypropptr_rna);
8363
8364# ifdef USE_WEAKREFS
8365 self_property->in_weakreflist = nullptr;
8366# else
8367 UNUSED_VARS_NDEBUG(self_property);
8368# endif
8369
8370 return self;
8371}
8372
8373static PyObject *pyrna_prop_collection_iter(PyObject *self)
8374{
8375 BPy_PropertyRNA *self_property = reinterpret_cast<BPy_PropertyRNA *>(self);
8376 return pyrna_prop_collection_iter_CreatePyObject(&self_property->ptr.value(),
8377 self_property->prop);
8378}
8379
8380static PyObject *pyrna_prop_collection_iter_next(PyObject *self)
8381{
8382 BPy_PropertyCollectionIterRNA *self_property = reinterpret_cast<BPy_PropertyCollectionIterRNA *>(
8383 self);
8384 if (self_property->iter->valid == false) {
8385 /* Free collection iterator immediately before tp_dealloc, to break cycles the GC can not
8386 * solve, between e.g. USE_PYRNA_STRUCT_REFERENCE and RNA_DepsgraphIterator.py_instance. */
8387 if (self_property->iter.has_value()) {
8388 RNA_property_collection_end(&self_property->iter.value());
8389 self_property->iter.reset();
8390 }
8391 PyErr_SetNone(PyExc_StopIteration);
8392 return nullptr;
8393 }
8394
8395 PyObject *iter_data = pyrna_struct_CreatePyObject(&self_property->iter->ptr);
8396
8397# ifdef USE_PYRNA_STRUCT_REFERENCE
8398 if (iter_data) { /* Unlikely, but may fail. */
8399 BPy_StructRNA *iter_data_struct = reinterpret_cast<BPy_StructRNA *>(iter_data);
8400 if (iter_data != Py_None) {
8401 /* hold a reference to the iterator since it may have
8402 * allocated memory `pyrna` needs. eg: introspecting dynamic enum's. */
8403 /* TODO: we could have an API call to know if this is
8404 * needed since most collections don't */
8405 pyrna_struct_reference_set(iter_data_struct, self);
8406 }
8407 }
8408# endif /* !USE_PYRNA_STRUCT_REFERENCE */
8409
8410 RNA_property_collection_next(&self_property->iter.value());
8411
8412 return iter_data;
8413}
8414
8415/* --- collection iterator: end --- */
8416#endif /* !USE_PYRNA_ITER */
8417
8419
8420/*-----------------------BPy_PropertyRNA method def------------------------------*/
8421
8422/* -------------------------------------------------------------------- */
8425
8426static void pyrna_func_dealloc(PyObject *self);
8427
8428PyTypeObject pyrna_func_Type = {
8429 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
8430 /*tp_name*/ "bpy_func",
8431 /*tp_basicsize*/ sizeof(BPy_FunctionRNA),
8432 /*tp_itemsize*/ 0,
8433 /*tp_dealloc*/ pyrna_func_dealloc,
8434 /*tp_vectorcall_offset*/ offsetof(BPy_FunctionRNA, vectorcall),
8435 /*tp_getattr*/ nullptr,
8436 /*tp_setattr*/ nullptr,
8437 /*tp_as_async*/ nullptr,
8438 /*tp_repr*/ reinterpret_cast<reprfunc>(pyrna_func_repr),
8439 /*tp_as_number*/ nullptr,
8440 /*tp_as_sequence*/ nullptr,
8441 /*tp_as_mapping*/ nullptr,
8442 /*tp_hash*/ nullptr,
8443 /*tp_call*/ PyVectorcall_Call,
8444 /*tp_str*/ nullptr,
8445 /*tp_getattro*/ nullptr,
8446 /*tp_setattro*/ nullptr,
8447 /*tp_as_buffer*/ nullptr,
8448 /*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_VECTORCALL,
8449 /*tp_doc*/ nullptr,
8450 /*tp_traverse*/ nullptr,
8451 /*tp_clear*/ nullptr,
8452 /*tp_richcompare*/ nullptr,
8453#ifdef USE_WEAKREFS
8454 /*tp_weaklistoffset*/ offsetof(BPy_PropertyRNA, in_weakreflist),
8455#else
8456 /*tp_weaklistoffset*/ 0,
8457#endif
8458 /*tp_iter*/ nullptr,
8459 /*tp_iternext*/ nullptr,
8460 /*tp_methods*/ nullptr,
8461 /*tp_members*/ nullptr,
8462 /*tp_getset*/ pyrna_func_getseters,
8463 /*tp_base*/ nullptr,
8464 /*tp_dict*/ nullptr,
8465 /*tp_descr_get*/ nullptr,
8466 /*tp_descr_set*/ nullptr,
8467 /*tp_dictoffset*/ 0,
8468 /*tp_init*/ nullptr,
8469 /*tp_alloc*/ nullptr,
8470 /*tp_new*/ nullptr,
8471 /*tp_free*/ nullptr,
8472 /*tp_is_gc*/ nullptr,
8473 /*tp_bases*/ nullptr,
8474 /*tp_mro*/ nullptr,
8475 /*tp_cache*/ nullptr,
8476 /*tp_subclasses*/ nullptr,
8477 /*tp_weaklist*/ nullptr,
8478 /*tp_del*/ nullptr,
8479 /*tp_version_tag*/ 0,
8480 /*tp_finalize*/ nullptr,
8481 /*tp_vectorcall*/ nullptr,
8482};
8483
8484static PyObject *pyrna_func_CreatePyObject(const PointerRNA *ptr, FunctionRNA *func)
8485{
8486 PyObject *self = pyrna_func_Type.tp_alloc(&pyrna_func_Type, 0);
8487 BPy_FunctionRNA *pyfunc = reinterpret_cast<BPy_FunctionRNA *>(self);
8488 if (pyfunc) {
8489 pyfunc->func = func;
8490 pyfunc->ptr = *ptr;
8492 }
8493
8494 if (!pyfunc) {
8495 PyErr_SetString(PyExc_MemoryError, "couldn't create bpy_func object");
8496 return nullptr;
8497 }
8498
8499 BLI_assert(pyfunc->ptr.has_value());
8500
8501 return reinterpret_cast<PyObject *>(pyfunc);
8502}
8503
8504static void pyrna_func_dealloc(PyObject *self)
8505{
8506 /* Save the current exception, if any. */
8507 PyObject *error_type, *error_value, *error_traceback;
8508 PyErr_Fetch(&error_type, &error_value, &error_traceback);
8509
8510 BPy_FunctionRNA *self_func = reinterpret_cast<BPy_FunctionRNA *>(self);
8511
8512#ifdef USE_WEAKREFS
8513 if (self_func->in_weakreflist != nullptr) {
8514 PyObject_ClearWeakRefs(self);
8515 }
8516#endif
8517
8518 self_func->ptr.~optional();
8519
8520 Py_TYPE(self)->tp_free(self);
8521
8522 /* Restore the saved exception. */
8523 PyErr_Restore(error_type, error_value, error_traceback);
8524}
8525
8527
8528static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
8529{
8530 Py_INCREF(newclass);
8531
8532 if (PyObject *oldclass = static_cast<PyObject *>(RNA_struct_py_type_get(srna))) {
8533 PyC_ObSpit("RNA WAS SET - ", oldclass);
8534 Py_DECREF(oldclass);
8535 }
8536 RNA_struct_py_type_set(srna, static_cast<void *>(newclass)); /* Store for later use */
8537
8538 /* Not 100% needed, but useful,
8539 * having an instance within a type looks wrong, but this instance _is_ an RNA type. */
8540
8541 /* Python deals with the circular reference. */
8542 PointerRNA ptr = RNA_pointer_create_discrete(nullptr, RNA_Struct, srna);
8543
8544 /* NOTE: using `pyrna_struct_CreatePyObject(&ptr)` is close to what is needed,
8545 * however the it isn't correct because the result of:
8546 * `type(bpy.types.Object.bl_rna) == bpy.types.Object`.
8547 * In this case the type of `bl_rna` should be `bpy.types.Struct`.
8548 * This is passed in explicitly, while #pyrna_struct_CreatePyObject could
8549 * take this as an argument it's such a corner case that using a lower level
8550 * function that takes the type is preferable. */
8551 {
8552 BLI_assert(RNA_struct_instance(&ptr) == nullptr);
8553 PyTypeObject *tp = reinterpret_cast<PyTypeObject *>(pyrna_srna_Subtype(RNA_Struct));
8554 PyObject *item = pyrna_struct_CreatePyObject_from_type(&ptr, tp, nullptr);
8555 Py_DECREF(tp); /* `srna` owns, can't hold a reference. */
8556
8557 /* NOTE: must set the class not the `__dict__`
8558 * else the internal slots are not updated correctly. */
8559 PyObject_SetAttr(newclass, bpy_intern_str_bl_rna, item);
8560 Py_DECREF(item);
8561 }
8562
8563 /* Add `staticmethod` and `classmethod` functions. */
8564 {
8565 const PointerRNA func_ptr = {nullptr, srna, nullptr};
8567 for (const std::unique_ptr<FunctionRNA> &link : lb) {
8568 FunctionRNA *func = link.get();
8569 const int flag = RNA_function_flag(func);
8570 if ((flag & FUNC_NO_SELF) && /* Is `staticmethod` or `classmethod`. */
8571 (flag & FUNC_REGISTER) == false) /* Is not for registration. */
8572 {
8573 /* We may want to set the type of this later. */
8574 PyObject *func_py = pyrna_func_CreatePyObject(&func_ptr, func);
8575 PyObject_SetAttrString(newclass, RNA_function_identifier(func), func_py);
8576 Py_DECREF(func_py);
8577 }
8578 }
8579 }
8580
8581 /* Done with RNA instance. */
8582}
8583
8587static PyObject *pyrna_srna_PyBase(StructRNA *srna)
8588{
8589 /* Assume RNA_struct_py_type_get(srna) was already checked. */
8590 StructRNA *base;
8591
8592 PyObject *py_base = nullptr;
8593
8594 /* Get the base type. */
8595 base = RNA_struct_base(srna);
8596
8597 if (base && base != srna) {
8598 // printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna);
8599 py_base = pyrna_srna_Subtype(base); //, bpy_types_dict);
8600 Py_DECREF(py_base); /* `srna` owns, this is only to pass as an argument. */
8601 }
8602
8603 if (py_base == nullptr) {
8604 py_base = reinterpret_cast<PyObject *>(&pyrna_struct_Type);
8605 }
8606
8607 return py_base;
8608}
8609
8614static PyObject *bpy_types_dict = nullptr;
8615void BPY_rna_types_dict_set(PyObject *dict)
8616{
8617 bpy_types_dict = dict; /* Borrow. */
8618}
8619
8625static PyObject *pyrna_srna_ExternalType(StructRNA *srna)
8626{
8628
8629 const char *idname = RNA_struct_identifier(srna);
8630 PyObject *newclass = PyDict_GetItemString(bpy_types_dict, idname);
8631
8632 /* Sanity check, could skip this unless in debug mode. */
8633 if (newclass) {
8634 PyObject *base_compare = pyrna_srna_PyBase(srna);
8635 /* Can't do this because it gets super-classes values! */
8636 // PyObject *slots = PyObject_GetAttrString(newclass, "__slots__");
8637 /* Can do this, but faster not to. */
8638 // PyObject *bases = PyObject_GetAttrString(newclass, "__bases__");
8639 PyObject *tp_bases = (reinterpret_cast<PyTypeObject *>(newclass))->tp_bases;
8640 PyObject *tp_slots = PyDict_GetItem((reinterpret_cast<PyTypeObject *>(newclass))->tp_dict,
8642
8643 if (tp_slots == nullptr) {
8644 CLOG_ERROR(
8645 BPY_LOG_RNA, "expected class '%s' to have __slots__ defined, see _bpy_types.py", idname);
8646 newclass = nullptr;
8647 }
8648 else if (PyTuple_GET_SIZE(tp_bases)) {
8649 PyObject *base = PyTuple_GET_ITEM(tp_bases, 0);
8650
8651 if (base_compare != base) {
8652 char pyob_info[256];
8653 PyC_ObSpitStr(pyob_info, sizeof(pyob_info), base_compare);
8655 "incorrect subclassing of SRNA '%s', expected '%s', see _bpy_types.py",
8656 idname,
8657 pyob_info);
8658 newclass = nullptr;
8659 }
8660 else {
8661 CLOG_TRACE(BPY_LOG_RNA, "SRNA sub-classed: '%s'", idname);
8662 }
8663 }
8664 }
8665
8666 return newclass;
8667}
8668
8674static PyObject *pyrna_srna_Subtype(StructRNA *srna)
8675{
8676 PyObject *newclass = nullptr;
8677
8678 /* Stupid/simple case. */
8679 if (srna == nullptr) {
8680 newclass = nullptr; /* Nothing to do. */
8681 } /* The class may have already been declared & allocated. */
8682 else if ((newclass = static_cast<PyObject *>(RNA_struct_py_type_get(srna)))) {
8683 /* Add a reference for the return value. */
8684 Py_INCREF(newclass);
8685 } /* Check if `_bpy_types.py` module has the class defined in it. */
8686 else if ((newclass = pyrna_srna_ExternalType(srna))) {
8687 pyrna_subtype_set_rna(newclass, srna);
8688 /* Add a reference for the return value. */
8689 Py_INCREF(newclass);
8690 } /* Create a new class instance with the C API
8691 * mainly for the purposing of matching the C/RNA type hierarchy. */
8692 else {
8693 /* subclass equivalents
8694 * - class myClass(myBase):
8695 * some = 'value' # or ...
8696 * - myClass = type(
8697 * name='myClass',
8698 * bases=(myBase,), dict={'__module__': 'bpy.types', '__slots__': ()}
8699 * )
8700 */
8701
8702 /* Assume `RNA_struct_py_type_get(srna)` was already checked. */
8703 PyObject *py_base = pyrna_srna_PyBase(srna);
8704 PyObject *metaclass;
8705 const char *idname = RNA_struct_identifier(srna);
8706
8707/* Remove `__doc__` for now because we don't need it to generate docs. */
8708#if 0
8709 const char *descr = RNA_struct_ui_description(srna);
8710 if (!descr) {
8711 descr = "(no docs)";
8712 }
8713#endif
8714
8716 !PyObject_IsSubclass(py_base,
8717 reinterpret_cast<PyObject *>(&pyrna_struct_meta_idprop_Type)))
8718 {
8719 metaclass = reinterpret_cast<PyObject *>(&pyrna_struct_meta_idprop_Type);
8720 }
8721 else {
8722 metaclass = reinterpret_cast<PyObject *>(&PyType_Type);
8723 }
8724
8725/* Always use O not N when calling, N causes refcount errors. */
8726#if 0
8727 newclass = PyObject_CallFunction(
8728 metaclass, "s(O) {sss()}", idname, py_base, "__module__", "bpy.types", "__slots__");
8729#else
8730 {
8731 /* Longhand of the call above. */
8732 PyObject *args, *item, *value;
8733 int ok;
8734
8735 args = PyTuple_New(3);
8736
8737 /* arg[0] (name=...) */
8738 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(idname));
8739
8740 /* arg[1] (bases=...) */
8741 PyTuple_SET_ITEM(args, 1, item = PyTuple_New(1));
8742 PyTuple_SET_ITEM(item, 0, Py_NewRef(py_base));
8743
8744 /* arg[2] (dict=...) */
8745 PyTuple_SET_ITEM(args, 2, item = PyDict_New());
8746 ok = PyDict_SetItem(item, bpy_intern_str___module__, bpy_intern_str_bpy_types);
8747 BLI_assert(ok != -1);
8748 ok = PyDict_SetItem(item, bpy_intern_str___slots__, value = PyTuple_New(0));
8749 Py_DECREF(value);
8750 BLI_assert(ok != -1);
8751
8752 newclass = PyObject_CallObject(metaclass, args);
8753 Py_DECREF(args);
8754
8755 (void)ok;
8756 }
8757#endif
8758
8759 /* Newclass will now have 2 ref's, ???,
8760 * probably 1 is internal since #Py_DECREF here segfaults. */
8761
8762 // PyC_ObSpit("new class ref", newclass);
8763
8764 if (newclass) {
8765 /* srna owns one, and the other is owned by the caller. */
8766 pyrna_subtype_set_rna(newclass, srna);
8767 }
8768 else {
8769 /* This should not happen. */
8770 CLOG_ERROR(BPY_LOG_RNA, "failed to register '%s'", idname);
8771 PyErr_Print();
8772 }
8773 }
8774
8775 return newclass;
8776}
8777
8782{
8783 if (ptr->type == RNA_Struct) {
8784 return static_cast<StructRNA *>(ptr->data);
8785 }
8786
8787 return ptr->type;
8788}
8789
8793static PyObject *pyrna_struct_Subtype(PointerRNA *ptr)
8794{
8795 return pyrna_srna_Subtype(srna_from_ptr(ptr));
8796}
8797
8798/*-----------------------CreatePyObject---------------------------------*/
8799
8807 PyTypeObject *tp,
8808 void **instance)
8809{
8810 /* Pass the PointerRNA to `__new__`/`__init__` functions as an opaque PyCapsule object. */
8811 PyObject *pyptr_rna = PyCapsule_New(
8812 const_cast<PointerRNA *>(ptr), BPy_capsule_PointerRNA_identifier, nullptr);
8813
8814 BPy_StructRNA *pyrna = nullptr;
8815 if (tp) {
8816 pyrna = reinterpret_cast<BPy_StructRNA *>(
8817 PyObject_CallOneArg(reinterpret_cast<PyObject *>(tp), pyptr_rna));
8818 }
8819 else {
8820 CLOG_WARN(BPY_LOG_RNA, "could not make type '%s'", RNA_struct_identifier(ptr->type));
8821
8822 pyrna = reinterpret_cast<BPy_StructRNA *>(
8823 PyObject_CallOneArg(reinterpret_cast<PyObject *>(&pyrna_struct_Type), pyptr_rna));
8824 }
8825
8826#ifdef USE_PYRNA_STRUCT_REFERENCE
8827 /* #PyType_GenericAlloc will have set tracking.
8828 * We only want tracking when `StructRNA.reference` has been set. */
8829 if (pyrna != nullptr) {
8830 PyObject_GC_UnTrack(pyrna);
8831 }
8832#endif
8833
8834#ifdef USE_WEAKREFS
8835 if (pyrna != nullptr) {
8836 pyrna->in_weakreflist = nullptr;
8837 }
8838#endif
8839
8840 BLI_assert(pyrna == nullptr || pyrna->ptr.has_value());
8841 Py_DECREF(pyptr_rna);
8842 if (pyrna == nullptr) {
8843 if (!PyErr_Occurred()) {
8844 PyErr_SetString(PyExc_MemoryError, "couldn't create bpy_struct object");
8845 }
8846 return nullptr;
8847 }
8848
8849 /* Blender's instance owns a reference (to avoid Python freeing it). */
8850 if (instance) {
8851 *instance = pyrna;
8852 Py_INCREF(pyrna);
8853 }
8854
8855#ifdef PYRNA_FREE_SUPPORT
8856 pyrna->freeptr = false;
8857#endif
8858
8859#ifdef USE_PYRNA_STRUCT_REFERENCE
8860 pyrna->reference = nullptr;
8861#endif
8862
8863 // PyC_ObSpit("NewStructRNA: ", (PyObject *)pyrna);
8864
8865#ifdef USE_PYRNA_INVALIDATE_WEAKREF
8866 if (ptr->owner_id) {
8867 id_weakref_pool_add(ptr->owner_id, (BPy_DummyPointerRNA *)pyrna);
8868 }
8869#endif
8870
8871 return reinterpret_cast<PyObject *>(pyrna);
8872}
8873
8875{
8876 /* NOTE: don't rely on this to return None since nullptr data with a valid type can often crash.
8877 * Operator RNA can have null data with a type set; only treat untyped pointers as None. */
8878 if (!ptr->has_type()) {
8879 Py_RETURN_NONE;
8880 }
8881
8882 BPy_StructRNA *pyrna = nullptr;
8883
8884 /* NOTE(@ideasman42): New in 2.8x, since not many types support instancing
8885 * we may want to use a flag to avoid looping over all classes. */
8886 void **instance = *ptr ? RNA_struct_instance(ptr) : nullptr;
8887 if (instance && *instance) {
8888 pyrna = static_cast<BPy_StructRNA *>(*instance);
8889
8890 /* Refine may have changed types after the first instance was created. */
8891 if (ptr->type == pyrna->ptr->type) {
8892 Py_INCREF(pyrna);
8893 return reinterpret_cast<PyObject *>(pyrna);
8894 }
8895
8896 /* Existing users will need to use 'type_recast' method. */
8897 Py_DECREF(pyrna);
8898 *instance = nullptr;
8899 /* Continue as if no instance was available. */
8900 }
8901
8902 PyTypeObject *tp = reinterpret_cast<PyTypeObject *>(pyrna_struct_Subtype(ptr));
8903 pyrna = reinterpret_cast<BPy_StructRNA *>(
8904 pyrna_struct_CreatePyObject_from_type(ptr, tp, instance));
8905 Py_XDECREF(tp); /* `srna` owns, can't hold a reference. */
8906
8907 return reinterpret_cast<PyObject *>(pyrna);
8908}
8909
8911{
8912 if (ptr->type == RNA_PrimitiveString) {
8913 const PrimitiveStringRNA *data = static_cast<const PrimitiveStringRNA *>(ptr->data);
8914 return PyC_UnicodeFromBytes(data->value);
8915 }
8916 if (ptr->type == RNA_PrimitiveInt) {
8917 const PrimitiveIntRNA *data = static_cast<const PrimitiveIntRNA *>(ptr->data);
8918 return PyLong_FromLong(data->value);
8919 }
8920 if (ptr->type == RNA_PrimitiveFloat) {
8921 const PrimitiveFloatRNA *data = static_cast<const PrimitiveFloatRNA *>(ptr->data);
8922 return PyFloat_FromDouble(data->value);
8923 }
8924 if (ptr->type == RNA_PrimitiveBoolean) {
8925 const PrimitiveBooleanRNA *data = static_cast<const PrimitiveBooleanRNA *>(ptr->data);
8926 return PyBool_FromLong(data->value);
8927 }
8928 return pyrna_struct_CreatePyObject(ptr);
8929}
8930
8932{
8933 PyTypeObject *type;
8934 if (RNA_property_array_check(prop)) {
8935 type = &pyrna_prop_array_Type;
8936 }
8937 else if (RNA_property_type(prop) == PROP_COLLECTION) {
8938 if (RNA_property_flag(prop) & PROP_IDPROPERTY) {
8940 }
8941 else {
8943 }
8944 }
8945 else {
8946 type = &pyrna_prop_Type;
8947 }
8948
8949 /* Pass the PointerRNA and PropertyRNA to `__new__`/`__init__` functions as an opaque PyCapsule
8950 * object. */
8951 BPy_PropertyPointerRNA_Reference prop_ptr{ptr, prop};
8952 PyObject *pypropptr_rna = PyCapsule_New(
8953 &prop_ptr, BPy_PropertyPointerRNA_capsule_identifier, nullptr);
8954
8955 BPy_PropertyRNA *pyrna = reinterpret_cast<BPy_PropertyRNA *>(
8956 PyObject_CallOneArg(reinterpret_cast<PyObject *>(type), pypropptr_rna));
8957
8958 BLI_assert(pyrna == nullptr || pyrna->ptr.has_value());
8959 Py_DECREF(pypropptr_rna);
8960 if (pyrna == nullptr) {
8961 PyErr_SetString(PyExc_MemoryError, "couldn't create BPy_rna object");
8962 return nullptr;
8963 }
8964
8965#ifdef USE_WEAKREFS
8966 pyrna->in_weakreflist = nullptr;
8967#endif
8968
8969#ifdef USE_PYRNA_INVALIDATE_WEAKREF
8970 if (ptr->owner_id) {
8971 id_weakref_pool_add(ptr->owner_id, (BPy_DummyPointerRNA *)pyrna);
8972 }
8973#endif
8974
8975 return reinterpret_cast<PyObject *>(pyrna);
8976}
8977
8979{
8980 if (id) {
8982 return pyrna_struct_CreatePyObject(&ptr);
8983 }
8984
8985 Py_RETURN_NONE;
8986}
8987
8988bool pyrna_id_FromPyObject(PyObject *obj, ID **id)
8989{
8990 if (pyrna_id_CheckPyObject(obj)) {
8991 *id = (reinterpret_cast<BPy_StructRNA *>(obj))->ptr->owner_id;
8992 return true;
8993 }
8994
8995 *id = nullptr;
8996 return false;
8997}
8998
8999bool pyrna_id_CheckPyObject(PyObject *obj)
9000{
9001 return BPy_StructRNA_Check(obj) &&
9002 RNA_struct_is_ID((reinterpret_cast<BPy_StructRNA *>(obj))->ptr->type);
9003}
9004
9006{
9007#ifdef USE_MATHUTILS /* Register mathutils callbacks, ok to run more than once. */
9010#endif
9011
9012/* For some reason MSVC complains of these. */
9013#if defined(_MSC_VER)
9014 pyrna_struct_meta_idprop_Type.tp_base = &PyType_Type;
9015#endif
9016
9017 /* metaclass */
9018 if (PyType_Ready(&pyrna_struct_meta_idprop_Type) < 0) {
9019 return;
9020 }
9021
9022 if (PyType_Ready(&pyrna_struct_Type) < 0) {
9023 return;
9024 }
9025
9026 if (PyType_Ready(&pyrna_prop_Type) < 0) {
9027 return;
9028 }
9029
9030 if (PyType_Ready(&pyrna_prop_array_Type) < 0) {
9031 return;
9032 }
9033
9034 if (PyType_Ready(&pyrna_prop_collection_Type) < 0) {
9035 return;
9036 }
9037
9038 if (PyType_Ready(&pyrna_prop_collection_idprop_Type) < 0) {
9039 return;
9040 }
9041
9042 if (PyType_Ready(&pyrna_func_Type) < 0) {
9043 return;
9044 }
9045
9046#ifdef USE_PYRNA_ITER
9047 if (PyType_Ready(&pyrna_prop_collection_iter_Type) < 0) {
9048 return;
9049 }
9050#endif
9051
9052#ifdef USE_PYRNA_INVALIDATE_WEAKREF
9053 BLI_assert(id_weakref_pool == nullptr);
9054 id_weakref_pool = BLI_ghash_ptr_new("rna_global_pool");
9055#endif
9056}
9057
9059{
9060#ifdef USE_PYRNA_INVALIDATE_WEAKREF
9061 /* This can help track down which kinds of data were not released.
9062 * If they were in fact freed by Blender, printing their names
9063 * will crash giving a useful error with address sanitizer. The likely cause
9064 * for this list not being empty is a missing call to: #BKE_libblock_free_data_py. */
9065 const int id_weakref_pool_len = BLI_ghash_len(id_weakref_pool);
9066 if (id_weakref_pool_len != 0) {
9067 printf("Found %d unreleased ID's\n", id_weakref_pool_len);
9068 GHashIterator gh_iter;
9069 GHASH_ITER (gh_iter, id_weakref_pool) {
9070 ID *id = static_cast<ID *>(BLI_ghashIterator_getKey(&gh_iter));
9071 printf("ID: %s\n", id->name);
9072 }
9073 }
9074 BLI_ghash_free(id_weakref_pool, nullptr, id_weakref_pool_free_value_fn);
9075 id_weakref_pool = nullptr;
9076#endif
9077}
9078
9079/* 'bpy.data' from Python. */
9080static PointerRNA *rna_module_ptr = nullptr;
9082{
9083 BPy_StructRNA *pyrna;
9084
9085 /* For now, return the base RNA type rather than a real module. */
9087 pyrna = reinterpret_cast<BPy_StructRNA *>(pyrna_struct_CreatePyObject(&ptr));
9088
9089 rna_module_ptr = &pyrna->ptr.value();
9090 return reinterpret_cast<PyObject *>(pyrna);
9091}
9092
9094{
9095 if (rna_module_ptr) {
9096#if 0
9098#else
9099 rna_module_ptr->data = G_MAIN; /* Just set data is enough. */
9100#endif
9101 }
9102}
9103
9104#if 0
9105/* This is a way we can access docstrings for RNA types
9106 * without having the data-types in Blender. */
9107PyObject *BPY_rna_doc()
9108{
9109
9110 /* For now, return the base RNA type rather than a real module. */
9111 PointerRNA ptr = RNA_blender_rna_pointer_create();
9112
9113 return pyrna_struct_CreatePyObject(&ptr);
9114}
9115#endif
9116
9117/* -------------------------------------------------------------------- */
9120
9129 std::optional<PointerRNA> ptr;
9132};
9133
9134static PyObject *bpy_types_module_getattro(PyObject *self, PyObject *pyname)
9135{
9136 BPy_TypesModule_State *state = static_cast<BPy_TypesModule_State *>(PyModule_GetState(self));
9137 BLI_assert(state->ptr.has_value());
9138
9139 PointerRNA newptr;
9140 PyObject *ret;
9141 const char *name = PyUnicode_AsUTF8(pyname);
9142
9143 if (name == nullptr) {
9144 PyErr_SetString(PyExc_AttributeError, "bpy.types: __getattr__ must be a string");
9145 ret = nullptr;
9146 }
9147 else if (RNA_property_collection_lookup_string(&state->ptr.value(), state->prop, name, &newptr))
9148 {
9149 ret = pyrna_struct_Subtype(&newptr);
9150 if (ret == nullptr) {
9151 PyErr_Format(PyExc_RuntimeError,
9152 "bpy.types.%.200s subtype could not be generated, this is a bug!",
9153 PyUnicode_AsUTF8(pyname));
9154 }
9155 }
9156 else {
9157#if 0
9158 PyErr_Format(PyExc_AttributeError,
9159 "bpy.types.%.200s RNA_Struct does not exist",
9160 PyUnicode_AsUTF8(pyname));
9161 return nullptr;
9162#endif
9163 /* The error raised here will be displayed. */
9164 ret = PyObject_GenericGetAttr(self, pyname);
9165 }
9166
9167 return ret;
9168}
9169
9170static PyObject *bpy_types_module_dir(PyObject *self)
9171{
9172 BPy_TypesModule_State *state = static_cast<BPy_TypesModule_State *>(PyModule_GetState(self));
9173 BLI_assert(state->ptr.has_value());
9174
9175 PyObject *ret = PyList_New(0);
9176
9177 RNA_PROP_BEGIN (&state->ptr.value(), itemptr, state->prop) {
9178 StructRNA *srna = static_cast<StructRNA *>(itemptr.data);
9179 PyList_APPEND(ret, PyUnicode_FromString(RNA_struct_identifier(srna)));
9180 }
9182
9183 /* Include the modules `__dict__` for Python only types. */
9184 PyObject *submodule_dict = PyModule_GetDict(self);
9185 PyObject *key, *value;
9186 Py_ssize_t pos = 0;
9187 while (PyDict_Next(submodule_dict, &pos, &key, &value)) {
9188 PyList_Append(ret, key);
9189 }
9190 return ret;
9191}
9192
9193#ifdef __GNUC__
9194# ifdef __clang__
9195# pragma clang diagnostic push
9196# pragma clang diagnostic ignored "-Wcast-function-type"
9197# else
9198# pragma GCC diagnostic push
9199# pragma GCC diagnostic ignored "-Wcast-function-type"
9200# endif
9201#endif
9202
9203static PyMethodDef bpy_types_module_methods[] = {
9204 {"__getattr__", static_cast<PyCFunction>(bpy_types_module_getattro), METH_O, nullptr},
9205 {"__dir__", reinterpret_cast<PyCFunction>(bpy_types_module_dir), METH_NOARGS, nullptr},
9206 {nullptr, nullptr, 0, nullptr},
9207};
9208
9209#ifdef __GNUC__
9210# ifdef __clang__
9211# pragma clang diagnostic pop
9212# else
9213# pragma GCC diagnostic pop
9214# endif
9215#endif
9216
9217static void bpy_types_module_free(void *self)
9218{
9219 /* Module's `m_free` is quite different from `PyTypeObject` `tp_free`. It does not have to free
9220 * python-allocated memory (like the module state itself), but only memory managed outside of
9221 * Python. In that sense, it is way closer to `tp_finalize`. */
9222
9223 PyObject *submodule = static_cast<PyObject *>(self);
9225 PyModule_GetState(submodule));
9226
9227 state->ptr.~optional();
9228}
9229
9231 /* Wrap. */
9232 bpy_types_module_doc,
9233 "Access to internal Blender types.");
9234static PyModuleDef bpy_types_module_def = {
9235 /*m_base*/ PyModuleDef_HEAD_INIT,
9236 /*m_name*/ "bpy.types",
9237 /*m_doc*/ bpy_types_module_doc,
9238 /*m_size*/ sizeof(BPy_TypesModule_State),
9239 /*m_methods*/ bpy_types_module_methods,
9240 /*m_slots*/ nullptr,
9241 /*m_traverse*/ nullptr,
9242 /*m_clear*/ nullptr,
9243 /*m_free*/ bpy_types_module_free,
9244};
9245
9246PyObject *BPY_rna_types()
9247{
9248 PyObject *submodule = PyModule_Create(&bpy_types_module_def);
9250 PyModule_GetState(submodule));
9251
9253 state->prop = RNA_struct_find_property(&state->ptr.value(), "structs");
9254
9255 /* Internal base types we have no other accessors for. */
9256 {
9257 static PyTypeObject *pyrna_types[] = {
9265 };
9266
9267 PyObject *submodule_dict = PyModule_GetDict(submodule);
9268 for (int i = 0; i < ARRAY_SIZE(pyrna_types); i += 1) {
9269 PyDict_SetItemString(
9270 submodule_dict, pyrna_types[i]->tp_name, reinterpret_cast<PyObject *>(pyrna_types[i]));
9271 }
9272 }
9273
9274 return submodule;
9275}
9276
9278{
9279 /* NOTE: Blender is generally functional without running this logic
9280 * however failure set the classes `bl_rna` (via `pyrna_subtype_set_rna`)
9281 * means *partially* initialized classes exist.
9282 * It's simpler to avoid this altogether as it's a corner case Python developers should
9283 * not have to concern themselves with as it could cause errors with RNA introspection.
9284 *
9285 * If the classes are accessed via `bpy.types` they will be initialized correctly
9286 * however classes can also be accessed via `bpy.types.ID.__subclasses__()`
9287 * which doesn't ensure the `bl_rna` is set. See: #127127. */
9288
9290 PyModule_GetState(submodule));
9291 BLI_assert(state->ptr.has_value());
9292
9293 PyObject *arg_key, *arg_value;
9294 Py_ssize_t arg_pos = 0;
9295 while (PyDict_Next(bpy_types_dict, &arg_pos, &arg_key, &arg_value)) {
9296 const char *key_str = PyUnicode_AsUTF8(arg_key);
9297 if (key_str[0] == '_') {
9298 continue;
9299 }
9300
9302 PyObject_IsSubclass(arg_value, (PyObject *)&pyrna_struct_Type),
9303 "Members of _bpy_types.py which are not StructRNA sub-classes must use a \"_\" prefix!");
9304
9305 PointerRNA newptr;
9306 if (RNA_property_collection_lookup_string(&state->ptr.value(), state->prop, key_str, &newptr))
9307 {
9308 StructRNA *srna = srna_from_ptr(&newptr);
9309 /* Within the Python logic of `./scripts/modules/_bpy_types.py`
9310 * it's possible this was already initialized. */
9311 if (RNA_struct_py_type_get(srna) == nullptr) {
9312 pyrna_subtype_set_rna(arg_value, srna);
9313 }
9314 }
9315#ifndef NDEBUG
9316 else {
9317 /* Avoid noisy warnings based on build-options. */
9318# ifndef WITH_USD
9319 if (STREQ(key_str, "USDHook")) {
9320 continue;
9321 }
9322# endif
9323 CLOG_WARN(
9324 BPY_LOG_RNA, "_bpy_types.py defines \"%.200s\" which is not a known RNA type!", key_str);
9325 }
9326#endif
9327 }
9328}
9329
9331
9332/* -------------------------------------------------------------------- */
9337
9338StructRNA *pyrna_struct_as_srna(PyObject *self, const bool parent, const char *error_prefix)
9339{
9340 BPy_StructRNA *py_srna = nullptr;
9341 StructRNA *srna;
9342
9343 /* Unfortunately PyObject_GetAttrString won't look up this types tp_dict first :/ */
9344 if (PyType_Check(self)) {
9345 py_srna = reinterpret_cast<BPy_StructRNA *>(
9346 PyDict_GetItem((reinterpret_cast<PyTypeObject *>(self))->tp_dict, bpy_intern_str_bl_rna));
9347 Py_XINCREF(py_srna);
9348 }
9349
9350 if (parent) {
9351 /* be very careful with this since it will return a parent classes srna.
9352 * modifying this will do confusing stuff! */
9353 if (py_srna == nullptr) {
9354 py_srna = reinterpret_cast<BPy_StructRNA *>(PyObject_GetAttr(self, bpy_intern_str_bl_rna));
9355 }
9356 }
9357
9358 if (py_srna == nullptr) {
9359 PyErr_Format(PyExc_RuntimeError,
9360 "%.200s, missing bl_rna attribute from '%.200s' instance (may not be registered)",
9361 error_prefix,
9362 Py_TYPE(self)->tp_name);
9363 return nullptr;
9364 }
9365
9366 if (!BPy_StructRNA_Check(py_srna)) {
9367 PyErr_Format(PyExc_TypeError,
9368 "%.200s, bl_rna attribute wrong type '%.200s' on '%.200s'' instance",
9369 error_prefix,
9370 Py_TYPE(py_srna)->tp_name,
9371 Py_TYPE(self)->tp_name);
9372 Py_DECREF(py_srna);
9373 return nullptr;
9374 }
9375
9376 if (py_srna->ptr->type != RNA_Struct) {
9377 PyErr_Format(PyExc_TypeError,
9378 "%.200s, bl_rna attribute not a RNA_Struct, on '%.200s'' instance",
9379 error_prefix,
9380 Py_TYPE(self)->tp_name);
9381 Py_DECREF(py_srna);
9382 return nullptr;
9383 }
9384
9385 srna = static_cast<StructRNA *>(py_srna->ptr->data);
9386 Py_DECREF(py_srna);
9387
9388 return srna;
9389}
9390
9391const PointerRNA *pyrna_struct_as_ptr(PyObject *py_obj, const StructRNA *srna)
9392{
9393 BPy_StructRNA *bpy_srna = reinterpret_cast<BPy_StructRNA *>(py_obj);
9394 if (!BPy_StructRNA_Check(py_obj) || !RNA_struct_is_a(bpy_srna->ptr->type, srna)) {
9395 PyErr_Format(PyExc_TypeError,
9396 "Expected a \"bpy.types.%.200s\" not a \"%.200s\"",
9398 Py_TYPE(py_obj)->tp_name);
9399 return nullptr;
9400 }
9401 PYRNA_STRUCT_CHECK_OBJ(bpy_srna);
9402 return &bpy_srna->ptr.value();
9403}
9404
9405const PointerRNA *pyrna_struct_as_ptr_or_null(PyObject *py_obj, const StructRNA *srna)
9406{
9407 if (py_obj == Py_None) {
9408 static const PointerRNA null_ptr;
9409 return &null_ptr;
9410 }
9411 return pyrna_struct_as_ptr(py_obj, srna);
9412}
9413
9414int pyrna_struct_as_ptr_parse(PyObject *o, void *p)
9415{
9416 BPy_StructRNA_Parse *srna_parse = static_cast<BPy_StructRNA_Parse *>(p);
9417 BLI_assert(srna_parse->type != nullptr);
9418 srna_parse->ptr = pyrna_struct_as_ptr(o, srna_parse->type);
9419 if (srna_parse->ptr == nullptr) {
9420 return 0;
9421 }
9422 return 1;
9423}
9424
9425int pyrna_struct_as_ptr_or_null_parse(PyObject *o, void *p)
9426{
9427 BPy_StructRNA_Parse *srna_parse = static_cast<BPy_StructRNA_Parse *>(p);
9428 BLI_assert(srna_parse->type != nullptr);
9429 srna_parse->ptr = pyrna_struct_as_ptr_or_null(o, srna_parse->type);
9430 if (srna_parse->ptr == nullptr) {
9431 return 0;
9432 }
9433 return 1;
9434}
9435
9436/* Orphan functions, not sure where they should go. */
9437
9438StructRNA *srna_from_self(PyObject *self, const char *error_prefix)
9439{
9440 if (self == nullptr) {
9441 return nullptr;
9442 }
9443 if (PyCapsule_CheckExact(self)) {
9444 return static_cast<StructRNA *>(PyCapsule_GetPointer(self, nullptr));
9445 }
9446 if (PyType_Check(self) == 0) {
9447 return nullptr;
9448 }
9449
9450 /* These cases above not errors, they just mean the type was not compatible
9451 * After this any errors will be raised in the script. */
9452 return pyrna_struct_as_srna(self, false, error_prefix);
9453}
9454
9456
9457/* -------------------------------------------------------------------- */
9460
9461static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item)
9462{
9464 /* No error, ignoring. */
9465 return 0;
9466 }
9467
9468 /* We only care about results from C which
9469 * are for sure types, save some time with error */
9470 PyObject *py_func = static_cast<PyObject *>((reinterpret_cast<BPy_PropDeferred *>(item))->fn);
9471 PyObject *py_kw = (reinterpret_cast<BPy_PropDeferred *>(item))->kw;
9472
9473 /* Show the function name in errors to help give context. */
9474 BLI_assert(PyCFunction_CheckExact(py_func));
9475 PyMethodDef *py_func_method_def = (reinterpret_cast<PyCFunctionObject *>(py_func))->m_ml;
9476 const char *func_name = py_func_method_def->ml_name;
9477
9478 const char *key_str = PyUnicode_AsUTF8(key);
9479
9480 if (*key_str == '_') {
9481 PyErr_Format(PyExc_ValueError,
9482 "bpy_struct \"%.200s\" registration error: "
9483 "'%.200s' %.200s could not register because it starts with an '_'",
9485 key_str,
9486 func_name);
9487 return -1;
9488 }
9489
9490 PyObject *type = PyDict_GetItemString(py_kw, "type");
9491 StructRNA *type_srna = srna_from_self(type, "");
9492 if (type_srna) {
9494 PyCFunctionWithKeywords py_func_ref = *(
9495 PyCFunctionWithKeywords)(void *)PyCFunction_GET_FUNCTION(py_func);
9496 if (ELEM(py_func_ref, BPy_PointerProperty, BPy_CollectionProperty)) {
9498
9499 PyErr_Format(PyExc_ValueError,
9500 "bpy_struct \"%.200s\" registration error: "
9501 "'%.200s' %.200s could not register because "
9502 "this type doesn't support data-block properties",
9504 key_str,
9505 func_name);
9506 return -1;
9507 }
9508 }
9509 }
9510 }
9511
9512 PyObject *py_srna_cobject = PyCapsule_New(srna, nullptr, nullptr);
9513
9514 /* Not 100% nice :/, modifies the dict passed, should be ok. */
9515 PyDict_SetItem(py_kw, bpy_intern_str_attr, key);
9516
9517 PyObject *args_fake = PyTuple_New(1);
9518 PyTuple_SET_ITEM(args_fake, 0, py_srna_cobject);
9519
9520 PyObject *py_ret = PyObject_Call(py_func, args_fake, py_kw);
9521
9522 if (py_ret) {
9523 Py_DECREF(py_ret);
9524 Py_DECREF(args_fake); /* Free's py_srna_cobject too. */
9525 }
9526 else {
9527 /* _must_ print before decrefing args_fake. */
9528 PyErr_Print();
9529
9530 Py_DECREF(args_fake); /* Free's py_srna_cobject too. */
9531
9532 PyErr_Format(PyExc_ValueError,
9533 "bpy_struct \"%.200s\" registration error: "
9534 "'%.200s' %.200s could not register (see previous error)",
9536 key_str,
9537 func_name);
9538 return -1;
9539 }
9540
9541 return 0;
9542}
9543
9547static int pyrna_deferred_register_class_from_type_hints(StructRNA *srna, PyTypeObject *py_class)
9548{
9549 PyObject *annotations_dict = nullptr;
9550
9551 /* `typing.get_type_hints(py_class)` */
9552 {
9553 PyObject *typing_mod = PyImport_ImportModuleLevel("typing", nullptr, nullptr, nullptr, 0);
9554 if (typing_mod != nullptr) {
9555 PyObject *get_type_hints_fn = PyObject_GetAttrString(typing_mod, "get_type_hints");
9556 if (get_type_hints_fn != nullptr) {
9557 PyObject *args = PyTuple_New(1);
9558
9559 PyTuple_SET_ITEM(args, 0, (PyObject *)py_class);
9560 Py_INCREF(py_class);
9561
9562 annotations_dict = PyObject_CallObject(get_type_hints_fn, args);
9563
9564 Py_DECREF(args);
9565 Py_DECREF(get_type_hints_fn);
9566 }
9567 Py_DECREF(typing_mod);
9568 }
9569 }
9570
9571 int ret = 0;
9572 if (annotations_dict != nullptr) {
9573 if (PyDict_CheckExact(annotations_dict)) {
9574 PyObject *item, *key;
9575 Py_ssize_t pos = 0;
9576
9577 while (PyDict_Next(annotations_dict, &pos, &key, &item)) {
9578 ret = deferred_register_prop(srna, key, item);
9579 if (ret != 0) {
9580 break;
9581 }
9582 }
9583 }
9584 else {
9585 /* Should never happen, an error won't have been raised, so raise one. */
9586 PyErr_Format(PyExc_TypeError,
9587 "typing.get_type_hints returned: %.200s, expected dict\n",
9588 Py_TYPE(annotations_dict)->tp_name);
9589 ret = -1;
9590 }
9591
9592 Py_DECREF(annotations_dict);
9593 }
9594 else {
9595 BLI_assert(PyErr_Occurred());
9596 fprintf(stderr, "typing.get_type_hints failed with: %.200s\n", py_class->tp_name);
9597 ret = -1;
9598 }
9599
9600 return ret;
9601}
9602
9603static int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
9604{
9605 PyObject *annotations_dict;
9606 PyObject *item, *key;
9607 Py_ssize_t pos = 0;
9608 int ret = 0;
9609
9610 /* in both cases PyDict_CheckExact(class_dict) will be true even
9611 * though Operators have a metaclass dict namespace */
9612 if ((annotations_dict = PyDict_GetItem(class_dict, bpy_intern_str___annotations__)) &&
9613 PyDict_CheckExact(annotations_dict))
9614 {
9615 while (PyDict_Next(annotations_dict, &pos, &key, &item)) {
9616 ret = deferred_register_prop(srna, key, item);
9617
9618 if (ret != 0) {
9619 break;
9620 }
9621 }
9622 }
9623
9624 return ret;
9625}
9626
9627static int pyrna_deferred_register_class_recursive(StructRNA *srna, PyTypeObject *py_class)
9628{
9629 const int len = PyTuple_GET_SIZE(py_class->tp_bases);
9630 int i, ret;
9631
9632 /* First scan base classes for registerable properties. */
9633 for (i = 0; i < len; i++) {
9634 PyTypeObject *py_superclass = reinterpret_cast<PyTypeObject *> PyTuple_GET_ITEM(
9635 py_class->tp_bases, i);
9636
9637 /* the rules for using these base classes are not clear,
9638 * 'object' is of course not worth looking into and
9639 * existing subclasses of RNA would cause a lot more dictionary
9640 * looping then is needed (SomeOperator would scan Operator.__dict__)
9641 * which is harmless, but not at all useful.
9642 *
9643 * So only scan base classes which are not subclasses if blender types.
9644 * This best fits having 'mix-in' classes for operators and render engines.
9645 */
9646 if (py_superclass != &PyBaseObject_Type &&
9647 !PyObject_IsSubclass(reinterpret_cast<PyObject *>(py_superclass),
9648 reinterpret_cast<PyObject *>(&pyrna_struct_Type)))
9649 {
9650 ret = pyrna_deferred_register_class_recursive(srna, py_superclass);
9651
9652 if (ret != 0) {
9653 return ret;
9654 }
9655 }
9656 }
9657
9658 /* Not register out own properties. */
9659 /* getattr(..., "__dict__") returns a proxy. */
9660 return pyrna_deferred_register_props(srna, py_class->tp_dict);
9661}
9662
9663int pyrna_deferred_register_class(StructRNA *srna, PyTypeObject *py_class)
9664{
9665 /* Panels and Menus don't need this
9666 * save some time and skip the checks here */
9668 return 0;
9669 }
9670
9671#ifdef USE_POSTPONED_ANNOTATIONS
9672 const bool use_postponed_annotations = true;
9673#else
9674 const bool use_postponed_annotations = false;
9675#endif
9676
9677 if (use_postponed_annotations) {
9678 return pyrna_deferred_register_class_from_type_hints(srna, py_class);
9679 }
9680 return pyrna_deferred_register_class_recursive(srna, py_class);
9681}
9682
9683static int rna_function_register_arg_count(FunctionRNA *func, int *min_count)
9684{
9685 const ListBaseT<PropertyRNA> *lb = RNA_function_defined_parameters(func);
9686 const int flag = RNA_function_flag(func);
9687 const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
9688 int count = is_staticmethod ? 0 : 1;
9689 bool done_min_count = false;
9690
9691 for (const Link &link : lb->cast<Link>()) {
9692 PropertyRNA *parm = reinterpret_cast<PropertyRNA *>(const_cast<Link *>(&link));
9693 if (!(RNA_parameter_flag(parm) & PARM_OUTPUT)) {
9694 if (!done_min_count && (RNA_parameter_flag(parm) & PARM_PYFUNC_REGISTER_OPTIONAL)) {
9695 /* From now on, the following parameters are optional in a Python function. */
9696 if (min_count) {
9697 *min_count = count;
9698 }
9699 done_min_count = true;
9700 }
9701 count++;
9702 }
9703 }
9704
9705 if (!done_min_count && min_count) {
9706 *min_count = count;
9707 }
9708 return count;
9709}
9710
9712
9713/* -------------------------------------------------------------------- */
9718
9720 StructRNA *srna,
9721 void *py_data,
9722 bool *have_function)
9723{
9724 const char *class_type = RNA_struct_identifier(srna);
9725 StructRNA *srna_base = RNA_struct_base(srna);
9726 PyObject *py_class = static_cast<PyObject *>(py_data);
9727 PyObject *base_class = static_cast<PyObject *>(RNA_struct_py_type_get(srna));
9728 int i, arg_count, func_arg_count, func_arg_min_count = 0;
9729 const char *py_class_name = (reinterpret_cast<PyTypeObject *>(py_class))->tp_name; /* __name__ */
9730
9731 if (srna_base) {
9732 if (bpy_class_validate_recursive(dummy_ptr, srna_base, py_data, have_function) != 0) {
9733 return -1;
9734 }
9735 }
9736
9737 if (base_class) {
9738 if (!PyObject_IsSubclass(py_class, base_class)) {
9739 PyErr_Format(PyExc_TypeError,
9740 "expected %.200s subclass of class \"%.200s\"",
9741 class_type,
9742 py_class_name);
9743 return -1;
9744 }
9745 }
9746
9747 /* Verify callback functions. */
9749 i = 0;
9750 for (const std::unique_ptr<FunctionRNA> &link : lb_func) {
9751 FunctionRNA *func = link.get();
9752 const int flag = RNA_function_flag(func);
9753 if (!(flag & FUNC_REGISTER)) {
9754 continue;
9755 }
9756
9757 PyObject *item;
9758 switch (PyObject_GetOptionalAttrString(py_class, RNA_function_identifier(func), &item)) {
9759 case 1: {
9760 break;
9761 }
9762 case 0: {
9763 if ((flag & (FUNC_REGISTER_OPTIONAL & ~FUNC_REGISTER)) == 0) {
9764 PyErr_Format(PyExc_AttributeError,
9765 "expected %.200s, %.200s class to have an \"%.200s\" attribute",
9766 class_type,
9767 py_class_name,
9769 return -1;
9770 }
9771 break;
9772 }
9773 case -1: { /* Unexpected error, an exception will have been raise. */
9774 return -1;
9775 }
9776 }
9777
9778 have_function[i] = (item != nullptr);
9779 i++;
9780
9781 if (item == nullptr) {
9782 continue;
9783 }
9784
9785 /* TODO(@ideasman42): this is used for classmethod's too,
9786 * even though class methods should have 'FUNC_USE_SELF_TYPE' set, see Operator.poll for eg.
9787 * Keep this as-is since it's working, but we should be using
9788 * 'FUNC_USE_SELF_TYPE' for many functions. */
9789 const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
9790
9791 /* Store original so we can decrement its reference before returning. */
9792 PyObject *item_orig = item;
9793
9794 if (is_staticmethod) {
9795 if (PyMethod_Check(item) == 0) {
9796 PyErr_Format(PyExc_TypeError,
9797 "expected %.200s, %.200s class \"%.200s\" "
9798 "attribute to be a static/class method, not a %.200s",
9799 class_type,
9800 py_class_name,
9802 Py_TYPE(item)->tp_name);
9803 Py_DECREF(item_orig);
9804 return -1;
9805 }
9806 item = (reinterpret_cast<PyMethodObject *>(item))->im_func;
9807 }
9808 else {
9809 if (PyFunction_Check(item) == 0) {
9810 PyErr_Format(PyExc_TypeError,
9811 "expected %.200s, %.200s class \"%.200s\" "
9812 "attribute to be a function, not a %.200s",
9813 class_type,
9814 py_class_name,
9816 Py_TYPE(item)->tp_name);
9817 Py_DECREF(item_orig);
9818 return -1;
9819 }
9820 }
9821
9822 func_arg_count = rna_function_register_arg_count(func, &func_arg_min_count);
9823
9824 if (func_arg_count >= 0) { /* -1 if we don't care. */
9825 arg_count = (reinterpret_cast<PyCodeObject *>(PyFunction_GET_CODE(item))->co_argcount);
9826
9827 /* NOTE: the number of args we check for and the number of args we give to
9828 * `@staticmethods` are different (quirk of Python),
9829 * this is why #rna_function_register_arg_count() doesn't return the value -1. */
9830 if (is_staticmethod) {
9831 func_arg_count++;
9832 func_arg_min_count++;
9833 }
9834
9835 if (arg_count < func_arg_min_count || arg_count > func_arg_count) {
9836 if (func_arg_min_count != func_arg_count) {
9837 PyErr_Format(
9838 PyExc_ValueError,
9839 "expected %.200s, %.200s class \"%.200s\" function to have between %d and %d "
9840 "args, found %d",
9841 class_type,
9842 py_class_name,
9844 func_arg_count,
9845 func_arg_min_count,
9846 arg_count);
9847 }
9848 else {
9849 PyErr_Format(
9850 PyExc_ValueError,
9851 "expected %.200s, %.200s class \"%.200s\" function to have %d args, found %d",
9852 class_type,
9853 py_class_name,
9855 func_arg_count,
9856 arg_count);
9857 }
9858 Py_DECREF(item_orig);
9859 return -1;
9860 }
9861 }
9862 Py_DECREF(item_orig);
9863 }
9864
9865 /* Allow Python `__name__` to be used for `bl_idname` for convenience. */
9866 struct {
9867 const char *rna_attr;
9868 PyObject *py_attr;
9869 } bpy_property_substitutions[] = {
9870 {"bl_idname", bpy_intern_str___name__},
9871 {"bl_description", bpy_intern_str___doc__},
9872 };
9873
9874 /* Verify properties. */
9875 const ListBaseT<PropertyRNA> *lb_prop = RNA_struct_type_properties(srna);
9876 for (Link &link : *reinterpret_cast<const ListBaseT<Link> *>(lb_prop)) {
9877 PropertyRNA *prop = reinterpret_cast<PropertyRNA *>(&link);
9878 const int flag = RNA_property_flag(prop);
9879
9880 if (!(flag & PROP_REGISTER)) {
9881 continue;
9882 }
9883
9884 const char *identifier = RNA_property_identifier(prop);
9885 PyObject *item = nullptr;
9886 switch (PyObject_GetOptionalAttrString(py_class, identifier, &item)) {
9887 case 1: { /* Found. */
9888 if (pyrna_py_to_prop(dummy_ptr, prop, nullptr, item, "validating class:", nullptr) != 0) {
9889 Py_DECREF(item);
9890 return -1;
9891 }
9892 Py_DECREF(item);
9893 break;
9894 }
9895 case -1: { /* Not found (an unexpected error). */
9896 /* Typically the attribute will exist or not, in previous releases all errors
9897 * were assumed to be missing attributes, so print the error and move on. */
9898 PyErr_Print();
9899 [[fallthrough]];
9900 }
9901 case 0: { /* Not found, check for fallbacks. */
9902
9903 /* Sneaky workaround to use the class name as the `bl_idname`. */
9904 int i;
9905 for (i = 0; i < ARRAY_SIZE(bpy_property_substitutions); i += 1) {
9906 if (STREQ(identifier, bpy_property_substitutions[i].rna_attr)) {
9907 break;
9908 }
9909 }
9910
9911 if (i < ARRAY_SIZE(bpy_property_substitutions)) {
9912 PyObject *py_attr = bpy_property_substitutions[i].py_attr;
9913 switch (PyObject_GetOptionalAttr(py_class, py_attr, &item)) {
9914 case 1: { /* Found. */
9915 if (item == Py_None) [[unlikely]] {
9916 Py_DECREF(item);
9917 item = nullptr;
9918 }
9919 else {
9920 if (pyrna_py_to_prop(
9921 dummy_ptr, prop, nullptr, item, "validating class:", nullptr) != 0)
9922 {
9923 Py_DECREF(item);
9924 return -1;
9925 }
9926 Py_DECREF(item);
9927 }
9928 break;
9929 }
9930 case -1: { /* Not found (an unexpected error). */
9931 PyErr_Print();
9932 break;
9933 }
9934 }
9935 }
9936
9937 if (item == nullptr && ((flag & PROP_REGISTER_OPTIONAL) != PROP_REGISTER_OPTIONAL)) {
9938 PyErr_Format(PyExc_AttributeError,
9939 "expected %.200s, %.200s class to have an \"%.200s\" attribute",
9940 class_type,
9941 py_class_name,
9942 identifier);
9943 return -1;
9944 }
9945 break;
9946 }
9947 }
9948 }
9949
9950 return 0;
9951}
9952
9953static int bpy_class_validate(PointerRNA *dummy_ptr, void *py_data, bool *have_function)
9954{
9955 return bpy_class_validate_recursive(dummy_ptr, dummy_ptr->type, py_data, have_function);
9956}
9957
9958/* TODO: multiple return values like with RNA functions. */
9960{
9961 PyObject *args;
9962 PyObject *ret = nullptr, *py_srna = nullptr, *py_class_instance = nullptr, *parmitem;
9963 PyTypeObject *py_class;
9964 PropertyRNA *parm;
9965 ParameterIterator iter;
9966 PointerRNA funcptr;
9967 int err = 0, i, ret_len = 0;
9968 const int flag = RNA_function_flag(func);
9969 const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
9970 const bool is_classmethod = (flag & FUNC_NO_SELF) && (flag & FUNC_USE_SELF_TYPE);
9971
9972 PropertyRNA *pret_single = nullptr;
9973 void *retdata_single = nullptr;
9974
9975 PyGILState_STATE gilstate;
9976
9977#ifdef USE_PEDANTIC_WRITE
9978 const bool is_readonly_init = !(RNA_struct_is_a(ptr->type, RNA_Operator) ||
9979 RNA_struct_is_a(ptr->type, RNA_Gizmo));
9980 // const char *func_id = RNA_function_identifier(func); /* UNUSED */
9981 /* Testing, for correctness, not operator and not draw function. */
9982 const bool is_readonly = !(RNA_function_flag(func) & FUNC_ALLOW_WRITE);
9983#endif
9984
9985 py_class = static_cast<PyTypeObject *>(RNA_struct_py_type_get(ptr->type));
9986 /* Rare case. can happen when registering subclasses. */
9987 if (py_class == nullptr) {
9989 "unable to get Python class for RNA struct '%.200s'",
9991 return -1;
9992 }
9993
9994 /* XXX, this is needed because render engine calls without a context
9995 * this should be supported at some point, but at the moment it's not! */
9996 if (C == nullptr) {
9997 C = BPY_context_get();
9998 }
9999
10000 bpy_context_set(C, &gilstate);
10001
10002 /* Annoying! We need to check if the screen gets set to nullptr which is a
10003 * hint that the file was actually re-loaded. */
10004 const bool is_valid_wm = (CTX_wm_manager(C) != nullptr);
10005
10006 if (!(is_staticmethod || is_classmethod)) {
10007 /* Some data-types (operator, render engine) can store PyObjects for re-use. */
10008 if (*ptr) {
10009 void **instance = RNA_struct_instance(ptr);
10010
10011 if (instance) {
10012 if (*instance) {
10013 py_class_instance = static_cast<PyObject *>(*instance);
10014 Py_INCREF(py_class_instance);
10015 }
10016 }
10017 }
10018 /* End exception. */
10019
10020 if (py_class_instance == nullptr) {
10021 py_srna = pyrna_struct_CreatePyObject(ptr);
10022 }
10023
10024 if (py_class_instance) {
10025 /* Special case, instance is cached. */
10026 }
10027 else if (py_srna == nullptr) {
10028 py_class_instance = nullptr;
10029 if (PyErr_Occurred()) {
10030 err = -1; /* So the error is not overridden below. */
10031 }
10032 }
10033 else if (py_srna == Py_None) { /* Probably won't ever happen, but possible. */
10034 Py_DECREF(py_srna);
10035 py_class_instance = nullptr;
10036 if (PyErr_Occurred()) {
10037 err = -1; /* So the error is not overridden below. */
10038 }
10039 }
10040 else {
10041#if 0
10042 /* Skip the code below and call init directly on the allocated 'py_srna'
10043 * otherwise __init__() always needs to take a second self argument, see pyrna_struct_new().
10044 * Although this is annoying to have to implement a part of Python's
10045 * typeobject.c:type_call().
10046 */
10047 if (py_class->tp_init) {
10048# ifdef USE_PEDANTIC_WRITE
10049 const int prev_write = rna_disallow_writes;
10050 rna_disallow_writes = is_readonly_init ? false :
10051 true; /* Only operators can write on __init__. */
10052# endif
10053
10054 /* True in most cases even when the class itself doesn't define an __init__ function. */
10055 args = PyTuple_New(0);
10056 if (py_class->tp_init(py_srna, args, nullptr) < 0) {
10057 Py_DECREF(py_srna);
10058 py_srna = nullptr;
10059 /* Err set below. */
10060 }
10061 Py_DECREF(args);
10062# ifdef USE_PEDANTIC_WRITE
10063 rna_disallow_writes = prev_write;
10064# endif
10065 }
10066 py_class_instance = py_srna;
10067
10068#else
10069# ifdef USE_PEDANTIC_WRITE
10070 const int prev_write = rna_disallow_writes;
10071 rna_disallow_writes = is_readonly_init ? false :
10072 true; /* Only operators can write on __init__. */
10073# endif
10074
10075/* 'almost' all the time calling the class isn't needed.
10076 * We could just do... */
10077# if 0
10078 py_class_instance = py_srna;
10079 Py_INCREF(py_class_instance);
10080# endif
10081 /*
10082 * This would work fine, but means __init__ functions wouldn't run.
10083 * None of Blender's default scripts use __init__ but it's nice to call it
10084 * for general correctness. just to note why this is here when it could be safely removed.
10085 */
10086 py_class_instance = PyObject_CallOneArg(reinterpret_cast<PyObject *>(py_class), py_srna);
10087
10088# ifdef USE_PEDANTIC_WRITE
10089 rna_disallow_writes = prev_write;
10090# endif
10091
10092#endif
10093
10094 if (py_class_instance == nullptr) {
10095 if (PyErr_Occurred()) {
10096 err = -1; /* So the error is not overridden below. */
10097 }
10098 }
10099
10100 Py_DECREF(py_srna);
10101 }
10102 }
10103
10104 /* Initializing the class worked, now run its invoke function. */
10105 if (err != -1 && (is_staticmethod || is_classmethod || py_class_instance)) {
10106 PyObject *item = PyObject_GetAttrString(reinterpret_cast<PyObject *>(py_class),
10108
10109 const bool item_type_valid = (item != nullptr) &&
10110 (is_staticmethod ? PyMethod_Check(item) : PyFunction_Check(item));
10111 if (item_type_valid) {
10112 funcptr = RNA_pointer_create_discrete(nullptr, RNA_Function, func);
10113 int arg_count;
10114
10115 /* NOTE: registration will have already checked the argument count matches
10116 * #rna_function_register_arg_count so there is no need to inspect the RNA function. */
10117
10118 if (is_staticmethod) {
10119 arg_count = (reinterpret_cast<PyCodeObject *>(
10120 PyFunction_GET_CODE(((PyMethodObject *)item)->im_func)))
10121 ->co_argcount -
10122 1;
10123 }
10124 else {
10125 arg_count = (reinterpret_cast<PyCodeObject *>(PyFunction_GET_CODE(item)))->co_argcount;
10126 }
10127 args = PyTuple_New(arg_count); /* First arg is included in 'item'. */
10128
10129 if (is_staticmethod) {
10130 i = 0;
10131 }
10132 else if (is_classmethod) {
10133 PyTuple_SET_ITEM(args, 0, (PyObject *)py_class);
10134 i = 1;
10135 }
10136 else {
10137 PyTuple_SET_ITEM(args, 0, py_class_instance);
10138 i = 1;
10139 }
10140
10141 RNA_parameter_list_begin(parms, &iter);
10142
10143 /* Parse function parameters. */
10144 for (; iter.valid; RNA_parameter_list_next(&iter)) {
10145 parm = iter.parm;
10146
10147 /* Only useful for single argument returns, we'll need another list loop for multiple. */
10148 if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
10149 ret_len++;
10150 if (pret_single == nullptr) {
10151 pret_single = parm;
10152 retdata_single = iter.data;
10153 }
10154
10155 continue;
10156 }
10157
10158 if (i < arg_count) {
10159 parmitem = pyrna_param_to_py(&funcptr, parm, iter.data);
10160 PyTuple_SET_ITEM(args, i, parmitem);
10161 i++;
10162 }
10163 }
10164
10165#ifdef USE_PEDANTIC_WRITE
10166 /* Handle nested draw calls, see: #89253. */
10167 const bool rna_disallow_writes_prev = rna_disallow_writes;
10168 rna_disallow_writes = is_readonly ? true : false;
10169#endif
10170 /* *** Main Caller *** */
10171
10172 ret = PyObject_Call(item, args, nullptr);
10173
10174 /* *** Done Calling *** */
10175
10176#ifdef USE_PEDANTIC_WRITE
10177 rna_disallow_writes = rna_disallow_writes_prev;
10178#endif
10179
10181 Py_DECREF(item);
10182 Py_DECREF(args);
10183 }
10184 else {
10185 PyErr_Print();
10186 PyErr_Format(PyExc_TypeError,
10187 "could not find function %.200s in %.200s to execute callback",
10190 err = -1;
10191 }
10192 }
10193 else {
10194 /* The error may be already set if the class instance couldn't be created. */
10195 if (err != -1) {
10196 PyErr_Format(PyExc_RuntimeError,
10197 "could not create instance of %.200s to call callback function '%.200s'",
10200 err = -1;
10201 }
10202 }
10203
10204 if (ret == nullptr) { /* Covers py_class_instance failing too. */
10205 err = -1;
10206 }
10207 else {
10208 if (ret_len == 0 && ret != Py_None) {
10209 PyErr_Format(PyExc_RuntimeError,
10210 "expected class %.200s, function %.200s to return None, not %.200s",
10213 Py_TYPE(ret)->tp_name);
10214 err = -1;
10215 }
10216 else if (ret_len == 1) {
10217 err = pyrna_py_to_prop(&funcptr, pret_single, retdata_single, ret, "", nullptr);
10218
10219 /* When calling operator functions only gives `Function.result` with no line number
10220 * since the function has finished calling on error, re-raise the exception with more
10221 * information since it would be slow to create prefix on every call
10222 * (when there are no errors). */
10223 if (err == -1) {
10224 PyC_Err_Format_Prefix(PyExc_RuntimeError,
10225 "class %.200s, function %.200s: incompatible return value ",
10228 }
10229 }
10230 else if (ret_len > 1) {
10231
10232 if (PyTuple_Check(ret) == 0) {
10233 PyErr_Format(
10234 PyExc_RuntimeError,
10235 "expected class %.200s, function %.200s to return a tuple of size %d, not %.200s",
10238 ret_len,
10239 Py_TYPE(ret)->tp_name);
10240 err = -1;
10241 }
10242 else if (PyTuple_GET_SIZE(ret) != ret_len) {
10243 PyErr_Format(PyExc_RuntimeError,
10244 "class %.200s, function %.200s to returned %d items, expected %d",
10247 PyTuple_GET_SIZE(ret),
10248 ret_len);
10249 err = -1;
10250 }
10251 else {
10252
10253 RNA_parameter_list_begin(parms, &iter);
10254
10255 /* Parse function parameters. */
10256 for (i = 0; iter.valid; RNA_parameter_list_next(&iter)) {
10257 parm = iter.parm;
10258
10259 /* Only useful for single argument returns, we'll need another list loop for multiple. */
10260 if (RNA_parameter_flag(parm) & PARM_OUTPUT) {
10261 err = pyrna_py_to_prop(&funcptr,
10262 parm,
10263 iter.data,
10264 PyTuple_GET_ITEM(ret, i++),
10265 "calling class function:",
10266 nullptr);
10267 if (err) {
10268 break;
10269 }
10270 }
10271 }
10272
10274 }
10275 }
10276 Py_DECREF(ret);
10277 }
10278
10279 if (err != 0) {
10280 ReportList *reports;
10281 /* Alert the user, else they won't know unless they see the console. */
10282 if ((!is_staticmethod) && (!is_classmethod) && (*ptr) &&
10283 RNA_struct_is_a(ptr->type, RNA_Operator) &&
10284 (is_valid_wm == (CTX_wm_manager(C) != nullptr)))
10285 {
10286 wmOperator *op = static_cast<wmOperator *>(ptr->data);
10287 reports = op->reports;
10288 }
10289 else {
10290 /* Won't alert users, but they can view in 'info' space. */
10291 reports = CTX_wm_reports(C);
10292 }
10293
10294 if (reports) {
10295 BPy_errors_to_report(reports);
10296 }
10297
10298 /* Also print in the console for Python. */
10299 PyErr_Print();
10300 /* Print a small line at ERROR level so that tests that rely on --debug-exit-on-error can
10301 * fail. This assumes that the majority of the information is already seen in the console via
10302 * PyErr_Print and should not be duplicated */
10304 "Python script error in %.200s.%.200s",
10307 }
10308
10309 bpy_context_clear(C, &gilstate);
10310
10311 return err;
10312}
10313
10317static void bpy_class_free_ex(PyObject *self, bool decref)
10318{
10319#ifdef WITH_PYTHON_MODULE
10320 /* This can happen when Python has exited before all Blender's RNA types have been freed.
10321 * In this Python memory management can't run.
10322 *
10323 * NOTE(@ideasman42): While I wasn't able to redo locally, it resolves the problem.
10324 * This happens:
10325 * - With AUDASPACE on macOS, see: #125376.
10326 * - With the build-bot on Linux, see: #135195.
10327 * Ideally this would be resolved
10328 * by correcting the order classes are freed (before Python exits). */
10329 if (!Py_IsInitialized()) {
10330 return;
10331 }
10332#endif
10333
10334 PyGILState_STATE gilstate = PyGILState_Ensure();
10335
10336 /* Breaks re-registering classes. */
10337 // PyDict_Clear(((PyTypeObject *)self)->tp_dict);
10338
10339 /* Remove the RNA attribute instead. */
10340
10341 /* NOTE: it's important to use `delattr` instead of `PyDict_DelItem`
10342 * to ensure the internal slots are updated (which is also used for assignment). */
10343 if (PyObject_DelAttr(self, bpy_intern_str_bl_rna) == -1) {
10344 PyErr_Clear();
10345 }
10346
10347#if 0 /* Needs further investigation, too annoying so quiet for now. */
10348 if (G.debug & G_DEBUG_PYTHON) {
10349 if (self->ob_refcnt > 1) {
10350 PyC_ObSpit("zombie class - reference should be 1", self);
10351 }
10352 }
10353#endif
10354
10355 if (decref) {
10356 Py_DECREF(self);
10357 }
10358
10359 PyGILState_Release(gilstate);
10360}
10361
10362static void bpy_class_free(void *pyob_ptr)
10363{
10364 /* Don't remove a reference because the argument passed in is from #ExtensionRNA::data
10365 * which doesn't own the reference.
10366 * This value is typically stored in #StructRNA::py_type which is handled separately. */
10367 bool decref = false;
10368 bpy_class_free_ex(static_cast<PyObject *>(pyob_ptr), decref);
10369}
10370
10374static PyTypeObject *bpy_class_check_any_bases_registered(PyTypeObject *cls)
10375{
10376 if (PyObject *bases = cls->tp_bases) {
10377 const int bases_num = PyTuple_GET_SIZE(bases);
10378 for (int i = 0; i < bases_num; i++) {
10379 PyTypeObject *base_cls = reinterpret_cast<PyTypeObject *> PyTuple_GET_ITEM(bases, i);
10380 BLI_assert(PyType_Check(base_cls));
10381 if (base_cls->tp_dict) {
10382 if (BPy_StructRNA *py_srna = reinterpret_cast<BPy_StructRNA *>(
10383 PyDict_GetItem(base_cls->tp_dict, bpy_intern_str_bl_rna)))
10384 {
10385 if (const StructRNA *srna = static_cast<const StructRNA *>(py_srna->ptr->data)) {
10386 if (srna->flag & STRUCT_RUNTIME) {
10387 return base_cls;
10388 }
10389 }
10390 }
10391 }
10392
10393 if (PyTypeObject *base_cls_test = bpy_class_check_any_bases_registered(base_cls)) {
10394 return base_cls_test;
10395 }
10396 }
10397 }
10398 return nullptr;
10399}
10400
10404static PyTypeObject *bpy_class_check_any_subclasses_registered(PyTypeObject *cls)
10405{
10406 PyTypeObject *result = nullptr;
10407 PyObject *subclasses = static_cast<PyObject *>(cls->tp_subclasses);
10408 if (subclasses) {
10409 BLI_assert(PyDict_CheckExact(subclasses));
10410 PyObject *key = nullptr;
10411 Py_ssize_t pos = 0;
10412 PyObject *value = nullptr;
10413 while (PyDict_Next(subclasses, &pos, &key, &value)) {
10414 BLI_assert(PyWeakref_CheckRef(value));
10415 PyObject *value_ref = pyweakref_get_ref(value);
10416 if (!value_ref) {
10417 continue;
10418 }
10419
10420 PyTypeObject *sub_cls = reinterpret_cast<PyTypeObject *>(value_ref);
10421 if (sub_cls->tp_dict) {
10422 if (BPy_StructRNA *py_srna = reinterpret_cast<BPy_StructRNA *>(
10423 PyDict_GetItem(sub_cls->tp_dict, bpy_intern_str_bl_rna)))
10424 {
10425 if (const StructRNA *srna = static_cast<const StructRNA *>(py_srna->ptr->data)) {
10426 if (srna->flag & STRUCT_RUNTIME) {
10427 result = sub_cls;
10428 }
10429 }
10430 }
10431 }
10432
10433 if (!result) {
10435 }
10436 /* NOTE: `result` is now a borrowed reference,
10437 * Acceptable since the type is kept alive by its instances and defining module. */
10438 Py_DECREF(value_ref);
10439
10440 if (result) {
10441 break;
10442 }
10443 }
10444 }
10445 return result;
10446}
10447
10449{
10450 /* NOTE: This isn't essential to run on startup, since sub-types will lazy initialize.
10451 * But keep running in debug mode so we get immediate notification of bad class hierarchy
10452 * or any errors in `_bpy_types.py` at load time, so errors don't go unnoticed. */
10453
10454#ifndef NDEBUG
10455 PyGILState_STATE gilstate = PyGILState_Ensure();
10456
10457 PropertyRNA *prop;
10458
10459 /* Avoid doing this lookup for every getattr. */
10461 prop = RNA_struct_find_property(&ptr, "structs");
10462
10463 RNA_PROP_BEGIN (&ptr, itemptr, prop) {
10464 PyObject *item = pyrna_struct_Subtype(&itemptr);
10465 if (item == nullptr) {
10466 if (PyErr_Occurred()) {
10467 PyErr_Print();
10468 }
10469 }
10470 else {
10471 Py_DECREF(item);
10472 }
10473 }
10475
10476 PyGILState_Release(gilstate);
10477#endif /* !NDEBUG */
10478}
10479
10481{
10482 PyObject *py_ptr = static_cast<PyObject *>(RNA_struct_py_type_get(srna));
10483
10484 if (py_ptr) {
10485 /* Remove a reference because `srna` owns it. */
10486 bool decref = true;
10487 bpy_class_free_ex(py_ptr, decref);
10488 RNA_struct_py_type_set(srna, nullptr);
10489 }
10490}
10491
10493
10494/* -------------------------------------------------------------------- */
10497
10498#define BPY_TYPEDEF_REGISTERABLE_DOC \
10499 "type[" \
10500 ":class:`bpy.types.Panel` | " \
10501 ":class:`bpy.types.UIList` | " \
10502 ":class:`bpy.types.Menu` | " \
10503 ":class:`bpy.types.Header` | " \
10504 ":class:`bpy.types.Operator` | " \
10505 ":class:`bpy.types.KeyingSetInfo` | " \
10506 ":class:`bpy.types.RenderEngine` | " \
10507 ":class:`bpy.types.AssetShelf` | " \
10508 ":class:`bpy.types.FileHandler` | " \
10509 ":class:`bpy.types.PropertyGroup` | " \
10510 ":class:`bpy.types.AddonPreferences` | " \
10511 ":class:`bpy.types.NodeTree` | " \
10512 ":class:`bpy.types.Node` | " \
10513 ":class:`bpy.types.NodeSocket` | " \
10514 ":class:`bpy.types.Gizmo` | " \
10515 ":class:`bpy.types.GizmoGroup`" \
10516 "]"
10517
10530 /* Wrap. */
10531 pyrna_register_class_doc,
10532 ".. function:: register_class(cls)\n"
10533 "\n"
10534 " Register a subclass of a Blender type class.\n"
10535 "\n"
10536 " :param cls: Registerable Blender class type.\n"
10537 " :type cls: " BPY_TYPEDEF_REGISTERABLE_DOC
10538 "\n"
10539 "\n"
10540 " :raises ValueError:\n"
10541 " if the class is not a subclass of a registerable blender class.\n"
10542 "\n"
10543 " .. note::\n"
10544 "\n"
10545 " If the class has a *register* class method it will be called\n"
10546 " before registration.\n");
10548 "register_class", pyrna_register_class, METH_O, pyrna_register_class_doc};
10549static PyObject *pyrna_register_class(PyObject * /*self*/, PyObject *py_class)
10550{
10551 bContext *C = nullptr;
10552 ReportList reports;
10554 StructRNA *srna;
10555 StructRNA *srna_new;
10556 const char *identifier;
10557 PyObject *py_cls_meth;
10558 const char *error_prefix = "register_class(...):";
10559
10560 if (!PyType_Check(py_class)) {
10561 PyErr_Format(PyExc_ValueError,
10562 "%s expected a class argument, not '%.200s'",
10563 error_prefix,
10564 Py_TYPE(py_class)->tp_name);
10565 return nullptr;
10566 }
10567
10568 if (PyDict_GetItem((reinterpret_cast<PyTypeObject *>(py_class))->tp_dict, bpy_intern_str_bl_rna))
10569 {
10570 PyErr_Format(PyExc_ValueError,
10571 "%s already registered as a subclass '%.200s'",
10572 error_prefix,
10573 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name);
10574 return nullptr;
10575 }
10576
10577 if (!pyrna_write_check()) {
10578 PyErr_Format(PyExc_RuntimeError,
10579 "%s cannot run in readonly state '%.200s'",
10580 error_prefix,
10581 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name);
10582 return nullptr;
10583 }
10584
10585 /* WARNING: gets parent classes srna, only for the register function. */
10586 srna = pyrna_struct_as_srna(py_class, true, "register_class(...):");
10587 if (srna == nullptr) {
10588 return nullptr;
10589 }
10590
10591 if (G.debug & G_DEBUG_PYTHON) [[unlikely]] {
10592 /* Warn if a class being registered uses an already registered base-class or sub-class,
10593 * both checks are needed otherwise the order of registering could suppress the warning.
10594 *
10595 * NOTE(@ideasman42) This is mainly to ensure good practice.
10596 * Mix-in classes are preferred when sharing functionality is needed,
10597 * otherwise changes to an Operator for example could unintentionally
10598 * break another operator that sub-classes it. */
10599 if (PyTypeObject *base_cls_test = bpy_class_check_any_bases_registered(
10600 reinterpret_cast<PyTypeObject *>(py_class)))
10601 {
10602 fprintf(stderr,
10603 "%s warning, %.200s: references and already registered base-class %.200s\n",
10604 error_prefix,
10605 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name,
10606 base_cls_test->tp_name);
10607 }
10608 if (PyTypeObject *sub_cls_test = bpy_class_check_any_subclasses_registered(
10609 reinterpret_cast<PyTypeObject *>(py_class)))
10610 {
10611 fprintf(stderr,
10612 "%s warning, %.200s: references and already registered sub-class %.200s\n",
10613 error_prefix,
10614 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name,
10615 sub_cls_test->tp_name);
10616 }
10617
10618 /* In practice it isn't useful to manipulate Python properties for `PropertyGroup`
10619 * instances since the Python objects themselves are not shared,
10620 * meaning a new Python instance is returned on each attribute access.
10621 * It may be useful to include other classes in this check - extend as needed.
10622 * See #141948. */
10624 if (!PyDict_GetItem((reinterpret_cast<PyTypeObject *>(py_class))->tp_dict,
10626 {
10627 fprintf(stderr,
10628 "%s warning, %.200s: is expected to contain a \"__slots__\" member "
10629 "to prevent arbitrary assignments.\n",
10630 error_prefix,
10631 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name);
10632 }
10633 }
10634 }
10635
10636/* Fails in some cases, so can't use this check, but would like to :| */
10637#if 0
10638 if (RNA_struct_py_type_get(srna)) {
10639 PyErr_Format(PyExc_ValueError,
10640 "%s %.200s's parent class %.200s is already registered, this is not allowed",
10641 error_prefix,
10642 ((PyTypeObject *)py_class)->tp_name,
10643 RNA_struct_identifier(srna));
10644 return nullptr;
10645 }
10646#endif
10647
10648 /* Check that we have a register callback for this type. */
10649 reg = RNA_struct_register(srna);
10650
10651 if (!reg) {
10652 PyErr_Format(PyExc_ValueError,
10653 "%s expected a subclass of a registerable "
10654 "RNA type (%.200s does not support registration)",
10655 error_prefix,
10656 RNA_struct_identifier(srna));
10657 return nullptr;
10658 }
10659
10660 /* Get the context, so register callback can do necessary refreshes. */
10661 C = BPY_context_get();
10662
10663 /* Call the register callback with reports & identifier. */
10665
10666 identifier = (reinterpret_cast<PyTypeObject *>(py_class))->tp_name;
10667
10668 srna_new = reg(CTX_data_main(C),
10669 &reports,
10670 py_class,
10671 identifier,
10675
10676 if (!reports.list.is_empty()) {
10677 const bool has_error = (BPy_reports_to_error(&reports, PyExc_RuntimeError, false) == -1);
10678 if (!has_error) {
10680 BPy_reports_write_stdout(&reports, error_prefix);
10681 }
10682 if (has_error) {
10683 BKE_reports_free(&reports);
10684 return nullptr;
10685 }
10686 }
10687 BKE_reports_free(&reports);
10688
10689 /* Python errors validating are not converted into reports so the check above will fail.
10690 * the cause for returning nullptr will be printed as an error */
10691 if (srna_new == nullptr) {
10692 return nullptr;
10693 }
10694
10695 /* Takes a reference to 'py_class'. */
10696 pyrna_subtype_set_rna(py_class, srna_new);
10697
10698 /* Old srna still references us, keep the check in case registering somehow can free it. */
10699 if (PyObject *old_py_class = static_cast<PyObject *>(RNA_struct_py_type_get(srna))) {
10700 RNA_struct_py_type_set(srna, nullptr);
10701 Py_DECREF(old_py_class);
10702 }
10703
10704 /* Can't use this because it returns a dict proxy
10705 *
10706 * item = PyObject_GetAttrString(py_class, "__dict__");
10707 */
10708 if (pyrna_deferred_register_class(srna_new, reinterpret_cast<PyTypeObject *>(py_class)) != 0) {
10709 return nullptr;
10710 }
10711
10712 /* Update 'struct name property' of the new type, in case:
10713 * - it already has a `name_property` defined;
10714 * - the current type has a different string property using the same identifier.
10715 *
10716 * This allows to keep using the default PropertyGroup `name` property (see the call to
10717 * #RNA_def_struct_name_property on 'PropertyGroup' StructRNA, in #rna_def_ID_properties), while
10718 * allowing to override it by another `name` string property in Python sub-types when required.
10719 */
10720 PropertyRNA *parent_name_prop = RNA_struct_name_property(srna_new);
10721 if (parent_name_prop) {
10723 srna_new, RNA_property_identifier(parent_name_prop));
10724 if (name_prop && name_prop != parent_name_prop && RNA_property_type(name_prop) == PROP_STRING)
10725 {
10726 RNA_def_struct_name_property(srna_new, name_prop, true);
10727 }
10728 else if (name_prop == RNA_struct_name_property(RNA_PropertyGroup)) {
10729 /* The `name` property inherited from 'PropertyGroup' is read-only, to avoid issues
10730 * with types that have a fixed set of ID properties. For backwards compatibility,
10731 * add a writable property here. */
10732 name_prop = RNA_def_property(srna_new, "name", PROP_STRING, PROP_NONE);
10733 RNA_def_property_ui_text(name_prop, "Name", "Unique name used in the code and scripting");
10734 RNA_def_property_duplicate_pointers(srna_new, name_prop);
10735 RNA_def_struct_name_property(srna_new, name_prop, true);
10736 }
10737 }
10738
10739 /* Call classed register method.
10740 * Note that zero falls through, no attribute, no error. */
10741 switch (PyObject_GetOptionalAttr(py_class, bpy_intern_str_register, &py_cls_meth)) {
10742 case 1: {
10743 PyObject *ret = PyObject_CallObject(py_cls_meth, nullptr);
10744 Py_DECREF(py_cls_meth);
10745 if (ret) {
10746 Py_DECREF(ret);
10747 }
10748 else {
10749 return nullptr;
10750 }
10751 break;
10752 }
10753 case -1: {
10754 return nullptr;
10755 }
10756 }
10757
10758 Py_RETURN_NONE;
10759}
10760
10762 StructRNA *srna,
10763 const char **r_prop_identifier)
10764{
10765 PropertyRNA *prop;
10766
10767 /* Verify properties. */
10768 const ListBaseT<PropertyRNA> *lb = RNA_struct_type_properties(srna);
10769
10770 for (const Link &link : lb->cast<Link>()) {
10771 prop = reinterpret_cast<PropertyRNA *>(const_cast<Link *>(&link));
10772 if (RNA_property_type(prop) == PROP_POINTER && !RNA_property_builtin(prop)) {
10773 PointerRNA tptr = RNA_pointer_create_discrete(nullptr, RNA_Struct, srna_props);
10774
10775 if (RNA_property_pointer_type(&tptr, prop) == srna) {
10776 *r_prop_identifier = RNA_property_identifier(prop);
10777 return 1;
10778 }
10779 }
10780 }
10781
10782 return 0;
10783}
10784
10786
10787/* -------------------------------------------------------------------- */
10790
10792 /* Wrap. */
10793 pyrna_unregister_class_doc,
10794 ".. function:: unregister_class(cls)\n"
10795 "\n"
10796 " Unload the Python class from blender.\n"
10797 "\n"
10798 " :param cls: Blender type class, \n"
10799 " see :func:`bpy.utils.register_class` for classes which can \n"
10800 " be registered.\n"
10801 " :type cls: " BPY_TYPEDEF_REGISTERABLE_DOC
10802 "\n"
10803 "\n"
10804 " .. note::\n"
10805 "\n"
10806 " If the class has an *unregister* class method it will be called\n"
10807 " before unregistering.\n");
10809 "unregister_class",
10811 METH_O,
10812 pyrna_unregister_class_doc,
10813};
10814static PyObject *pyrna_unregister_class(PyObject * /*self*/, PyObject *py_class)
10815{
10816 bContext *C = nullptr;
10818 StructRNA *srna;
10819 PyObject *py_cls_meth;
10820 const char *error_prefix = "unregister_class(...):";
10821
10822 if (!PyType_Check(py_class)) {
10823 PyErr_Format(PyExc_ValueError,
10824 "%s expected a class argument, not '%.200s'",
10825 error_prefix,
10826 Py_TYPE(py_class)->tp_name);
10827 return nullptr;
10828 }
10829
10830#if 0
10831 if (PyDict_GetItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna) == nullptr) {
10832 PyErr_Format(PyExc_ValueError, "%s not a registered as a subclass", error_prefix);
10833 return nullptr;
10834 }
10835#endif
10836
10837 if (!pyrna_write_check()) {
10838 PyErr_Format(PyExc_RuntimeError,
10839 "%s cannot run in readonly state '%.200s'",
10840 error_prefix,
10841 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name);
10842 return nullptr;
10843 }
10844
10845 srna = pyrna_struct_as_srna(py_class, false, error_prefix);
10846 if (srna == nullptr) {
10847 return nullptr;
10848 }
10849
10850 if ((srna->flag & STRUCT_RUNTIME) == 0) {
10851 PyErr_Format(PyExc_RuntimeError,
10852 "%s can't unregister a built-in class '%.200s'",
10853 error_prefix,
10854 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name);
10855 return nullptr;
10856 }
10857
10858 /* Check that we have a unregister callback for this type. */
10859 unreg = RNA_struct_unregister(srna);
10860
10861 if (!unreg) {
10862 PyErr_Format(PyExc_ValueError,
10863 "%s expected type '%.200s' subclassed from a registerable RNA type "
10864 "(unregister not supported)",
10865 error_prefix,
10866 (reinterpret_cast<PyTypeObject *>(py_class))->tp_name);
10867 return nullptr;
10868 }
10869
10870 /* Call classed unregister method.
10871 * Note that zero falls through, no attribute, no error. */
10872 switch (PyObject_GetOptionalAttr(py_class, bpy_intern_str_unregister, &py_cls_meth)) {
10873 case 1: {
10874 PyObject *ret = PyObject_CallObject(py_cls_meth, nullptr);
10875 Py_DECREF(py_cls_meth);
10876 if (ret) {
10877 Py_DECREF(ret);
10878 }
10879 else {
10880 return nullptr;
10881 }
10882 break;
10883 }
10884 case -1: {
10885 return nullptr;
10886 }
10887 }
10888
10889 /* Should happen all the time, however it's very slow. */
10890 if (G.debug & G_DEBUG_PYTHON) {
10891 /* Remove all properties using this class. */
10892 StructRNA *srna_iter;
10893 PropertyRNA *prop_rna;
10894 const char *prop_identifier = nullptr;
10895
10897 prop_rna = RNA_struct_find_property(&ptr_rna, "structs");
10898
10899 /* Loop over all structs. */
10900 RNA_PROP_BEGIN (&ptr_rna, itemptr, prop_rna) {
10901 srna_iter = static_cast<StructRNA *>(itemptr.data);
10902 if (pyrna_srna_contains_pointer_prop_srna(srna_iter, srna, &prop_identifier)) {
10903 break;
10904 }
10905 }
10907
10908 if (prop_identifier) {
10909 PyErr_Format(PyExc_RuntimeError,
10910 "%s cannot unregister %s because %s.%s pointer property is using this",
10911 error_prefix,
10913 RNA_struct_identifier(srna_iter),
10914 prop_identifier);
10915 return nullptr;
10916 }
10917 }
10918
10919 /* Get the context, so register callback can do necessary refreshes. */
10920 C = BPY_context_get();
10921
10922 /* Call unregister. */
10923 unreg(CTX_data_main(C), srna); /* Calls bpy_class_free, this decref's py_class. */
10924
10925 /* Typically `bpy_class_free` will have removed, remove here just in case. */
10926 if (PyDict_Contains(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna)) [[unlikely]] {
10927 if (PyDict_DelItem((reinterpret_cast<PyTypeObject *>(py_class))->tp_dict,
10928 bpy_intern_str_bl_rna) == -1)
10929 {
10930 PyErr_Clear();
10931 }
10932 }
10933
10934 Py_RETURN_NONE;
10935}
10936
10938
10939/* -------------------------------------------------------------------- */
10942
10943void pyrna_struct_type_extend_capi(StructRNA *srna, PyMethodDef *method, PyGetSetDef *getset)
10944{
10945 /* See 'add_methods' in Python's 'typeobject.c'. */
10946 PyTypeObject *type = reinterpret_cast<PyTypeObject *>(pyrna_srna_Subtype(srna));
10947 PyObject *dict = type->tp_dict;
10948 if (method != nullptr) {
10949 for (; method->ml_name != nullptr; method++) {
10950 PyObject *py_method;
10951
10952 if (method->ml_flags & METH_CLASS) {
10953 PyObject *cfunc = PyCFunction_New(method, (PyObject *)type);
10954 py_method = PyClassMethod_New(cfunc);
10955 Py_DECREF(cfunc);
10956 }
10957 else if (method->ml_flags & METH_STATIC) {
10958 py_method = PyCFunction_New(method, nullptr);
10959 }
10960 else {
10961 py_method = PyDescr_NewMethod(type, method);
10962 }
10963
10964 const int err = PyDict_SetItemString(dict, method->ml_name, py_method);
10965 Py_DECREF(py_method);
10966 BLI_assert(!(err < 0));
10967 UNUSED_VARS_NDEBUG(err);
10968 }
10969 }
10970
10971 if (getset != nullptr) {
10972 for (; getset->name != nullptr; getset++) {
10973 PyObject *descr = PyDescr_NewGetSet(type, getset);
10974 /* Ensure we're not overwriting anything that already exists. */
10975 BLI_assert(PyDict_GetItem(dict, PyDescr_NAME(descr)) == nullptr);
10976 PyDict_SetItem(dict, PyDescr_NAME(descr), descr);
10977 Py_DECREF(descr);
10978 }
10979 }
10980 Py_DECREF(type);
10981}
10982
10984
10985/* -------------------------------------------------------------------- */
10988
10989/* Access to the 'owner_id' so work-spaces can filter by add-on. */
10990
10991static PyObject *pyrna_bl_owner_id_get(PyObject * /*self*/)
10992{
10993 const char *name = RNA_struct_state_owner_get();
10994 if (name) {
10995 return PyUnicode_FromString(name);
10996 }
10997 Py_RETURN_NONE;
10998}
10999
11000static PyObject *pyrna_bl_owner_id_set(PyObject * /*self*/, PyObject *value)
11001{
11002 const char *name;
11003 if (value == Py_None) {
11004 name = nullptr;
11005 }
11006 else if (PyUnicode_Check(value)) {
11007 name = PyUnicode_AsUTF8(value);
11008 }
11009 else {
11010 PyErr_Format(PyExc_ValueError,
11011 "owner_set(...): "
11012 "expected None or a string, not '%.200s'",
11013 Py_TYPE(value)->tp_name);
11014 return nullptr;
11015 }
11017 Py_RETURN_NONE;
11018}
11019
11020#ifdef __GNUC__
11021# ifdef __clang__
11022# pragma clang diagnostic push
11023# pragma clang diagnostic ignored "-Wcast-function-type"
11024# else
11025# pragma GCC diagnostic push
11026# pragma GCC diagnostic ignored "-Wcast-function-type"
11027# endif
11028#endif
11029
11031 "_bl_owner_id_get",
11032 reinterpret_cast<PyCFunction>(pyrna_bl_owner_id_get),
11033 METH_NOARGS,
11034 nullptr,
11035};
11037 "_bl_owner_id_set",
11038 static_cast<PyCFunction>(pyrna_bl_owner_id_set),
11039 METH_O,
11040 nullptr,
11041};
11042
11043#ifdef __GNUC__
11044# ifdef __clang__
11045# pragma clang diagnostic pop
11046# else
11047# pragma GCC diagnostic pop
11048# endif
11049#endif
11050
11052
11053} // namespace blender
#define G_MAIN
#define ATTR_FALLTHROUGH
A dynamically sized string ADT.
#define GHASH_ITER(gh_iter_, ghash_)
Definition BLI_ghash.hh:320
#define STR_ELEM(...)
#define SNPRINTF_UTF8(dst, format,...)
#define STRNCPY_UTF8(dst, src)
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
bool CLG_quiet_get()
Definition clog.cc:942
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_TRACE(clg_ref,...)
Definition CLG_log.h:192
These structs are the foundation for all linked lists in the library system.
Read Blender memory allocation and freeing.
#define RNA_PROP_END
#define RNA_STRUCT_BEGIN(sptr, prop)
#define RNA_STRUCT_END
#define RNA_PROP_BEGIN(sptr, itemptr, prop)
#define RNA_ENUM_BITFLAG_SIZE
Definition RNA_types.hh:270
#define C
Definition RandGen.cpp:29
#define CLAMP(a, b, c)
#define BLI_assert_unreachable()
#define UNUSED_VARS(...)
#define STREQLEN(a, b, n)
#define STRINGIFY(x)
#define UNUSED_VARS_NDEBUG(...)
#define BLI_assert(a)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
#define STREQ(a, b)
#define CLAMP_MIN(a, b)
#define BPy_PropDeferred_CheckTypeExact(v)
Definition bpy_props.hh:39
#define PYRNA_STACK_ARRAY
Definition bpy_props.hh:41
#define MATHUTILS_CB_SUBTYPE_COLOR
Definition bpy_rna.cc:590
#define PROP_ALL_VECTOR_SUBTYPES
Definition bpy_rna.cc:818
#define BPY_DOC_ID_PROP_TYPE_NOTE
Definition bpy_rna.cc:171
#define PYRNA_PROP_COLLECTION_ABS_INDEX(ret_err)
Definition bpy_rna.cc:2413
#define MATHUTILS_CB_SUBTYPE_VEC
Definition bpy_rna.cc:588
#define MATHUTILS_CB_SUBTYPE_EUL
Definition bpy_rna.cc:587
#define BPY_TYPEDEF_REGISTERABLE_DOC
Definition bpy_rna.cc:10498
#define MATHUTILS_CB_SUBTYPE_QUAT
Definition bpy_rna.cc:589
#define PYRNA_STRUCT_IS_VALID(pysrna)
Definition bpy_rna.hh:113
#define BPy_StructRNA_CheckExact(v)
Definition bpy_rna.hh:77
#define PYRNA_STRUCT_CHECK_OBJ(obj)
Definition bpy_rna.hh:81
#define PYRNA_STRUCT_CHECK_INT(obj)
Definition bpy_rna.hh:86
#define PYRNA_STRUCT_CHECK_OBJ_UNLESS(obj, unless)
Definition bpy_rna.hh:103
#define PYRNA_PROP_CHECK_OBJ(obj)
Definition bpy_rna.hh:92
#define PYRNA_PROP_CHECK_INT(obj)
Definition bpy_rna.hh:97
#define BPy_PropertyRNA_CheckExact(v)
Definition bpy_rna.hh:79
#define BPy_StructRNA_Check(v)
Definition bpy_rna.hh:76
#define BPy_PropertyRNA_Check(v)
Definition bpy_rna.hh:78
btScalar max
UString()=default
constexpr bool is_empty() const
constexpr int64_t size() const
constexpr const char * data() const
#define offsetof(t, d)
#define FLT_MAX
#define INT_MAX
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
float length(VecOp< float, D >) RET
const int state
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
void free(Subdiv *subdiv)
Definition subdiv.cc:192
bNodeType * node_type_find(UString idname)
Definition node.cc:2883
UString node_type_find_alias(UString alias)
Definition node.cc:2892
std::string ptr_type(const ResourceString &str)
BMesh Iterators.
static PyObject * pyrna_prop_collection_values(BPy_PropertyRNA *self)
Definition bpy_rna.cc:5672
static PyMappingMethods pyrna_struct_as_mapping
Definition bpy_rna.cc:3791
char * RNA_property_string_get_alloc(PointerRNA *ptr, PropertyRNA *prop, char *fixedbuf, int fixedlen, int *r_len)
const char * BKE_idtype_idcode_to_name(short idcode)
Definition idtype.cc:261
PyTypeObject pyrna_func_Type
Definition bpy_rna.cc:8428
int RNA_property_array_length(PointerRNA *ptr, PropertyRNA *prop)
PointerRNA RNA_pointer_create_from_ancestor(const PointerRNA &ptr, const int ancestor_idx)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
bool pyrna_id_CheckPyObject(PyObject *obj)
Definition bpy_rna.cc:8999
int RNA_property_enum_bitflag_identifiers(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value, const char **r_identifier)
bool RNA_property_overridable_library_set(PointerRNA *, PropertyRNA *prop, const bool is_overridable)
void IDP_FreeFromGroup(IDProperty *group, IDProperty *prop) ATTR_NONNULL()
Definition idprop.cc:812
static PyObject * pyrna_struct_property_overridable_library_set(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:4084
size_t size_t size_t BLI_snprintf_utf8(char *__restrict dst, size_t dst_maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
void ** RNA_struct_instance(PointerRNA *ptr)
static void pyrna_struct_dealloc(PyObject *self)
Definition bpy_rna.cc:7713
static int prop_subscript_ass_array_slice__float_recursive(PyObject **value_items, float *value, int totdim, const int dimsize[], const float range[2])
Definition bpy_rna.cc:3157
static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
Definition bpy_rna.cc:2387
static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int, int index)
Definition bpy_rna.cc:678
static PyObject * pyrna_struct_pop(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:5748
unsigned __int64 uint64_t
Definition BKE_text.h:91
static PyObject * pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:3971
static PyObject * pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
Definition bpy_rna.cc:4875
PointerRNA RNA_property_pointer_get(PointerRNA *ptr, PropertyRNA *prop)
PyObject * bpy_intern_str___slots__
PyObject * bpy_intern_str___doc__
static PyMethodDef pyrna_struct_methods[]
Definition bpy_rna.cc:6637
void BLI_dynstr_appendf(DynStr *__restrict ds, const char *__restrict format,...) ATTR_PRINTF_FORMAT(2
static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
Definition bpy_rna.cc:3653
__int64 int64_t
Definition BKE_text.h:90
static int pyrna_struct_compare(BPy_StructRNA *a, BPy_StructRNA *b)
Definition bpy_rna.cc:997
bool RNA_struct_idprops_datablock_allowed(const StructRNA *type)
BLI_INLINE void * BLI_ghashIterator_getKey(GHashIterator *ghi) ATTR_WARN_UNUSED_RESULT
Definition BLI_ghash.hh:297
bool RNA_struct_system_idprops_check(StructRNA *srna)
static int pyrna_prop_collection_ass_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum, PyObject *value)
Definition bpy_rna.cc:2525
static void pyrna_prop_warn_deprecated(const PointerRNA *ptr, const PropertyRNA *prop, const DeprecatedRNA *deprecated)
Definition bpy_rna.cc:216
void RNA_def_property_ui_text(PropertyRNA *prop, const char *name, const char *description)
static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
Definition bpy_rna.cc:2403
PyObject * pyrna_struct_keyframe_delete(BPy_StructRNA *self, PyObject *args, PyObject *kw)
static PyObject * pyrna_struct_path_from_module(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:4202
static PyObject * bpy_types_dict
Definition bpy_rna.cc:8614
static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop, int arraydim, int arrayoffset, int start, int step, int slice_length, int array_length, PyObject *value_orig)
Definition bpy_rna.cc:3254
static PyObject * bpy_types_module_dir(PyObject *self)
Definition bpy_rna.cc:9170
char pyrna_struct_keyframe_insert_doc[]
static int bpy_class_validate_recursive(PointerRNA *dummy_ptr, StructRNA *srna, void *py_data, bool *have_function)
Definition bpy_rna.cc:9719
void RNA_property_float_get_array(PointerRNA *ptr, PropertyRNA *prop, float *values)
@ RPT_WARNING
Definition BKE_report.hh:40
int PyC_ParseBool(PyObject *o, void *p)
PointerRNA RNA_main_pointer_create(Main *main)
static long pyrna_prop_hash(BPy_PropertyRNA *self)
Definition bpy_rna.cc:1311
PropertyRNA * RNA_struct_find_property(PointerRNA *ptr, const char *identifier)
int pyrna_enum_bitfield_from_set(const EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
@ STRUCT_RUNTIME
bool RNA_struct_idprops_check(const StructRNA *srna)
PointerRNA RNA_pointer_recast(PointerRNA *ptr)
PyObject * BPY_rna_module()
Definition bpy_rna.cc:9081
void RNA_property_update(bContext *C, PointerRNA *ptr, PropertyRNA *prop)
static PyObject * pyrna_func_vectorcall(PyObject *callable, PyObject *const *args, size_t nargsf, PyObject *kwnames)
Definition bpy_rna.cc:7097
void RNA_property_pointer_set(PointerRNA *ptr, PropertyRNA *prop, PointerRNA ptr_value, ReportList *reports)
bool RNA_struct_is_a(const StructRNA *type, const StructRNA *srna)
static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
Definition bpy_rna.cc:3470
unsigned int uint
Definition BKE_text.h:55
int pyrna_prop_validity_check(const BPy_PropertyRNA *self)
Definition bpy_rna.cc:199
static int pyrna_prop_collection_type_check(BPy_PropertyRNA *self, PyObject *value)
Definition bpy_rna.cc:2968
static PyObject * pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, Py_ssize_t start, Py_ssize_t step, Py_ssize_t slice_length, Py_ssize_t array_length)
Definition bpy_rna.cc:2795
const char * RNA_function_ui_description(FunctionRNA *func)
static PyObject * pyrna_prop_str(BPy_PropertyRNA *self)
Definition bpy_rna.cc:1168
void RNA_property_string_set_bytes(PointerRNA *ptr, PropertyRNA *prop, const char *value, int len)
static PyObject * pyrna_struct_get_rna_type(BPy_PropertyRNA *self, void *)
Definition bpy_rna.cc:5551
static PyObject * pyrna_struct_id_properties_ui(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:4806
void BKE_reports_free(ReportList *reports)
Definition report.cc:106
PointerRNA RNA_blender_rna_pointer_create()
void BKE_report_print_level_set(ReportList *reports, eReportType level)
Definition report.cc:276
PyObject * pyrna_id_CreatePyObject(ID *id)
Definition bpy_rna.cc:8978
bool RNA_property_editable_flag(const PointerRNA *ptr, PropertyRNA *prop)
void BPY_id_release(ID *id)
Definition bpy_rna.cc:453
BPy_StructRNA * bpy_context_module
Definition bpy_rna.cc:100
bool RNA_property_enum_identifier(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value, const char **r_identifier)
static PyGetSetDef pyrna_prop_getseters[]
Definition bpy_rna.cc:5561
PointerRNA RNA_id_pointer_create(ID *id)
void * RNA_struct_py_type_get(StructRNA *srna)
std::optional< std::string > RNA_path_from_ID_to_property(const PointerRNA *ptr, PropertyRNA *prop)
Definition rna_path.cc:1237
std::optional< std::string > RNA_path_full_struct_py(const PointerRNA *ptr)
Definition rna_path.cc:1325
PyObject * Quaternion_CreatePyObject_cb(PyObject *cb_user, uchar cb_type, uchar cb_subtype)
void * BLI_ghash_lookup(const GHash *gh, const void *key) ATTR_WARN_UNUSED_RESULT
Definition BLI_ghash.cc:735
PropertyRNA * RNA_struct_type_find_property_no_base(StructRNA *srna, const UString identifier)
void RNA_property_float_set(PointerRNA *ptr, PropertyRNA *prop, float value)
void pyrna_context_clear(bContext *C)
Definition bpy_rna.cc:534
static PyNumberMethods pyrna_prop_array_as_number
Definition bpy_rna.cc:3566
PyMethodDef meth_bpy_owner_id_set
Definition bpy_rna.cc:11036
const char * RNA_property_identifier(const PropertyRNA *prop)
static int pyrna_prop_collection_ass_subscript(BPy_PropertyRNA *self, PyObject *key, PyObject *value)
Definition bpy_rna.cc:3011
void BPY_rna_exit()
Definition bpy_rna.cc:9058
eRNAStatus RNA_property_collection_move(PointerRNA *ptr, PropertyRNA *prop, int src_index, int dst_index)
static void pyrna_dir_members_py__add_keys(PyObject *list, PyObject *dict)
Definition bpy_rna.cc:4644
void RNA_property_boolean_get_array(PointerRNA *ptr, PropertyRNA *prop, bool *values)
static int rna_function_register_arg_count(FunctionRNA *func, int *min_count)
Definition bpy_rna.cc:9683
void pyrna_context_init(bContext *C)
Definition bpy_rna.cc:529
void BKE_reports_init(ReportList *reports, int flag)
Definition report.cc:91
static bool foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
Definition bpy_rna.cc:6074
void BPy_reports_write_stdout(const ReportList *reports, const char *header)
bool RNA_property_builtin(PropertyRNA *prop)
static PyObject * pyrna_func_repr(BPy_FunctionRNA *self)
Definition bpy_rna.cc:1297
int RNA_property_enum_get(PointerRNA *ptr, PropertyRNA *prop)
int(*)(BaseMathObject *, int) BaseMathSetFunc
Definition mathutils.hh:113
int pyrna_struct_validity_check(const BPy_StructRNA *pysrna)
Definition bpy_rna.cc:190
void RNA_property_enum_items(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
int RNA_property_collection_raw_get(ReportList *reports, PointerRNA *ptr, PropertyRNA *prop, const char *propname, void *array, RawPropertyType type, int len)
float RNA_property_float_get_index(PointerRNA *ptr, PropertyRNA *prop, int index)
IDProperty * IDP_GetPropertyFromGroup(const IDProperty *prop, StringRef name) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
Definition idprop.cc:818
int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const bool all_args, const char *error_prefix)
Definition bpy_rna.cc:1618
static PyObject * pyrna_prop_collection_iter_next(PyObject *self)
Definition bpy_rna.cc:8380
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
static Mathutils_Callback mathutils_rna_matrix_cb
Definition bpy_rna.cc:784
static void bpy_class_free(void *pyob_ptr)
Definition bpy_rna.cc:10362
static PyGetSetDef pyrna_struct_getseters[]
Definition bpy_rna.cc:5580
PyTypeObject pyrna_prop_Type
Definition bpy_rna.cc:7785
static PyMethodDef pyrna_prop_array_methods[]
Definition bpy_rna.cc:6781
static PyObject * pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
Definition bpy_rna.cc:1458
std::optional< std::string > RNA_path_from_ID_to_struct(const PointerRNA *ptr)
Definition rna_path.cc:1078
static PyObject * pyrna_struct_as_pointer(BPy_StructRNA *self)
Definition bpy_rna.cc:5809
static PyObject * pyrna_prop_collection_idprop_add(BPy_PropertyRNA *self)
Definition bpy_rna.cc:5403
const char * RNA_struct_state_owner_get()
PyObject * Euler_CreatePyObject(const float eul[3], const short order, PyTypeObject *base_type)
@ FUNC_USE_SELF_TYPE
@ FUNC_ALLOW_WRITE
@ FUNC_NO_SELF
Definition RNA_types.hh:998
@ FUNC_REGISTER_OPTIONAL
@ FUNC_REGISTER
char * BLI_strncpy_utf8(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
FunctionRNA * RNA_struct_find_function(StructRNA *srna, const char *identifier_c_str)
void RNA_parameter_list_next(ParameterIterator *iter)
void RNA_property_collection_begin(PointerRNA *ptr, PropertyRNA *prop, CollectionPropertyIterator *iter)
bool RNA_struct_idprops_contains_datablock(const StructRNA *type)
PyObject * BPy_IDGroup_MapDataToPy(IDProperty *prop)
void RNA_parameter_list_end(ParameterIterator *)
void * BLI_findstring(const ListBase *listbase, const char *id, int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:615
static PyObject * pyrna_register_class(PyObject *self, PyObject *py_class)
Definition bpy_rna.cc:10549
static PyObject * prop_subscript_ass_array_slice__as_seq_fast(PyObject *value, int length)
Definition bpy_rna.cc:3137
int(*)(BaseMathObject *, int) BaseMathGetFunc
Definition mathutils.hh:111
bool RNA_property_overridable_get(const PointerRNA *ptr, PropertyRNA *prop)
PyObject * BPy_Wrap_GetItems_View_WithID(ID *id, IDProperty *prop)
StructUnregisterFunc RNA_struct_unregister(StructRNA *type)
bool RNA_property_enum_value(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const char *identifier, int *r_value)
char pyrna_struct_keyframe_delete_doc[]
bool RNA_property_collection_assign_int(PointerRNA *ptr, PropertyRNA *prop, const int key, const PointerRNA *assign_ptr)
static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
Definition bpy_rna.cc:623
static PySequenceMethods pyrna_struct_as_sequence
Definition bpy_rna.cc:3707
static PyObject * pyrna_prop_array_iter(BPy_PropertyArrayRNA *self)
Definition bpy_rna.cc:6582
char * RNA_struct_name_get_alloc(PointerRNA *ptr, char *fixedbuf, int fixedlen, int *r_len)
static bool rna_id_write_error(PointerRNA *ptr, PyObject *key)
Definition bpy_rna.cc:478
void RNA_property_float_set_array(PointerRNA *ptr, PropertyRNA *prop, const float *values)
static PyObject * pyrna_prop_collection_subscript_str_lib_pair(BPy_PropertyRNA *self, PyObject *key, const char *err_prefix, const bool err_not_found)
Definition bpy_rna.cc:2740
static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *)
Definition bpy_rna.cc:7611
std::optional< std::string > RNA_path_from_real_ID_to_property_index(Main *bmain, const PointerRNA *ptr, PropertyRNA *prop, int index_dim, int index, ID **r_real_id)
Definition rna_path.cc:1242
static PyObject * pyrna_bl_owner_id_get(PyObject *)
Definition bpy_rna.cc:10991
void RNA_property_boolean_set_array(PointerRNA *ptr, PropertyRNA *prop, const bool *values)
ATTR_WARN_UNUSED_RESULT const BMVert * v
PropertyRNA * RNA_struct_iterator_property(StructRNA *type)
int RNA_property_collection_length(PointerRNA *ptr, PropertyRNA *prop)
void BPY_rna_types_dict_set(PyObject *dict)
Definition bpy_rna.cc:8615
static PyObject * pyrna_struct_is_property_overridable_library(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:4045
static int mathutils_rna_matrix_get(BaseMathObject *bmo, int)
Definition bpy_rna.cc:737
static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
Definition bpy_rna.cc:2376
static int pyrna_property_init(PyObject *self, PyObject *args, PyObject *)
Definition bpy_rna.cc:8050
static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *key)
Definition bpy_rna.cc:3622
static PyMethodDef pyrna_prop_collection_methods[]
Definition bpy_rna.cc:6794
PyObject * pyrna_struct_CreatePyObject(PointerRNA *ptr)
Definition bpy_rna.cc:8874
static PyObject * pyrna_struct_str(BPy_StructRNA *self)
Definition bpy_rna.cc:1075
PyTypeObject pyrna_struct_meta_idprop_Type
Definition bpy_rna.cc:7454
static PyObject * pyrna_prop_repr_ex(BPy_PropertyRNA *self, const int index_dim, const int index)
Definition bpy_rna.cc:1240
static PyModuleDef bpy_types_module_def
Definition bpy_rna.cc:9234
PyMethodDef meth_bpy_unregister_class
Definition bpy_rna.cc:10808
PyObject * BPy_Wrap_GetKeys_View_WithID(ID *id, IDProperty *prop)
PyObject * PyC_UnicodeFromBytes(const char *str)
static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item)
Definition bpy_rna.cc:9461
static PyObject * pyrna_prop_collection_foreach_set(BPy_PropertyRNA *self, PyObject *args)
Definition bpy_rna.cc:6380
static int pyrna_prop_collection_subscript_is_valid_or_error(const PyObject *value)
Definition bpy_rna.cc:2426
PyObject * Matrix_CreatePyObject_cb(PyObject *cb_user, const ushort col_num, const ushort row_num, uchar cb_type, uchar cb_subtype)
const ListBaseT< PropertyRNA > * RNA_struct_type_properties(StructRNA *srna)
PyObject * BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw)
void BLI_dynstr_free(DynStr *ds) ATTR_NONNULL()
static PyObject * pyrna_srna_ExternalType(StructRNA *srna)
Definition bpy_rna.cc:8625
int(*)(BaseMathObject *, int, int) BaseMathGetIndexFunc
Definition mathutils.hh:115
static PyObject * pyrna_prop_collection_getattro(BPy_PropertyRNA *self, PyObject *pyname)
Definition bpy_rna.cc:5278
StructRNA RNA_PropertyGroup
PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
Definition bpy_rna.cc:1533
static PyObject * pyrna_prop_collection_iter_new(PyTypeObject *type, PyObject *, PyObject *)
Definition bpy_rna.cc:8248
int pyrna_struct_as_ptr_or_null_parse(PyObject *o, void *p)
Definition bpy_rna.cc:9425
void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA *prop)
static PyMappingMethods pyrna_prop_collection_as_mapping
Definition bpy_rna.cc:3559
void BLI_ghash_insert(GHash *gh, void *key, void *val)
Definition BLI_ghash.cc:711
static PyMethodDef bpy_types_module_methods[]
Definition bpy_rna.cc:9203
PyObject * bpy_intern_str___annotations__
bool RNA_property_collection_remove(PointerRNA *ptr, PropertyRNA *prop, int key)
int RNA_function_flag(FunctionRNA *func)
static Mathutils_Callback mathutils_rna_array_cb
Definition bpy_rna.cc:726
bool BPy_errors_to_report(ReportList *reports)
ParameterList * RNA_parameter_list_create(ParameterList *parms, PointerRNA *, FunctionRNA *func)
PyObject * BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw)
static PyTypeObject pyrna_prop_collection_iter_Type
Definition bpy_rna.cc:8192
@ G_DEBUG_PYTHON
static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int, int index)
Definition bpy_rna.cc:692
bool RNA_property_boolean_get(PointerRNA *ptr, PropertyRNA *prop)
bool RNA_property_array_check(PropertyRNA *prop)
PyObject * pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args, PyObject *kw)
Global G
Definition blender.cc:57
void RNA_property_collection_add(PointerRNA *ptr, PropertyRNA *prop, PointerRNA *r_ptr)
static PyObject * pyrna_prop_collection_iter(PyObject *self)
Definition bpy_rna.cc:8373
void RNA_property_int_set_array(PointerRNA *ptr, PropertyRNA *prop, const int *values)
int(*)(BaseMathObject *) BaseMathCheckFunc
Definition mathutils.hh:109
void RNA_property_int_set(PointerRNA *ptr, PropertyRNA *prop, int value)
unsigned short uint16_t
Definition BKE_text.h:80
void BPY_rna_types_finalize_external_types(PyObject *submodule)
Definition bpy_rna.cc:9277
static PyObject * pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
Definition bpy_rna.cc:2580
PropertyRNA * RNA_def_property(StructOrFunctionRNA *cont_, const char *identifier_c_str, int type, int subtype)
PropertyType RNA_property_type(PropertyRNA *prop)
bool RNA_property_collection_lookup_string_has_fn(PropertyRNA *prop)
static PyObject * pyrna_prop_collection_get(BPy_PropertyRNA *self, PyObject *args)
Definition bpy_rna.cc:5832
static PyObject * pyrna_prop_collection_items(BPy_PropertyRNA *self)
Definition bpy_rna.cc:5635
const EnumPropertyItem rna_enum_property_type_items[]
Definition rna_rna.cc:45
static bool rna_disallow_writes
Definition bpy_rna.cc:476
static PyObject * pyrna_prop_array_repr(BPy_PropertyArrayRNA *self)
Definition bpy_rna.cc:1291
int(*)(BaseMathObject *, int, int) BaseMathSetIndexFunc
Definition mathutils.hh:117
static PyObject * pyrna_prop_collection_idprop_clear(BPy_PropertyRNA *self)
Definition bpy_rna.cc:5462
void BLI_ghashIterator_step(GHashIterator *ghi)
Definition BLI_ghash.cc:917
static PyNumberMethods pyrna_prop_collection_as_number
Definition bpy_rna.cc:3578
static void bpy_types_module_free(void *self)
Definition bpy_rna.cc:9217
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
int RNA_function_defined(FunctionRNA *func)
static int foreach_parse_args(BPy_PropertyRNA *self, PyObject *args, const char *function_name, const char **r_attr, PyObject **r_seq, int *r_tot, size_t *r_size, RawPropertyType *r_raw_type, int *r_attr_tot, bool *r_attr_signed)
Definition bpy_rna.cc:5961
PyObject * pyrna_py_from_array_index(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, int index)
PyObject * Vector_CreatePyObject(const float *vec, const int vec_num, PyTypeObject *base_type)
static void pyrna_func_error_prefix(BPy_FunctionRNA *self, PropertyRNA *parm, const int parm_index, char *error, const size_t error_maxncpy)
Definition bpy_rna.cc:7065
PyObject * pyrna_prop_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop)
Definition bpy_rna.cc:8931
void RNA_property_string_set(PointerRNA *ptr, PropertyRNA *prop, const char *value)
std::optional< std::string > RNA_path_from_real_ID_to_struct(Main *bmain, const PointerRNA *ptr, ID **r_real)
Definition rna_path.cc:1120
static PyObject * pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:4128
StructRNA * RNA_property_pointer_type(PointerRNA *ptr, PropertyRNA *prop)
PyObject * bpy_intern_str_bpy_types
static PyTypeObject * bpy_class_check_any_bases_registered(PyTypeObject *cls)
Definition bpy_rna.cc:10374
PyObject * bpy_intern_str___name__
unsigned char uchar
Definition BKE_text.h:58
PyObject * Matrix_CreatePyObject(const float *mat, const ushort col_num, const ushort row_num, PyTypeObject *base_type)
@ PROP_BOOLEAN
Definition RNA_types.hh:210
@ PROP_POINTER
Definition RNA_types.hh:215
@ PROP_STRING
Definition RNA_types.hh:213
@ PROP_COLLECTION
Definition RNA_types.hh:216
void BLI_ghash_free(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp)
Definition BLI_ghash.cc:866
static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
Definition bpy_rna.cc:3490
static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
Definition bpy_rna.cc:8528
PyObject * Quaternion_CreatePyObject(const float quat[4], PyTypeObject *base_type)
int pyrna_struct_as_ptr_parse(PyObject *o, void *p)
Definition bpy_rna.cc:9414
struct bContext * BPY_context_get()
static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *r_value, const char *error_prefix)
Definition bpy_rna.cc:1387
void RNA_property_int_get_array(PointerRNA *ptr, PropertyRNA *prop, int *values)
std::string RNA_path_from_ptr_to_property_index(const PointerRNA *ptr, PropertyRNA *prop, int index_dim, int index)
Definition rna_path.cc:1212
BMesh const char void * data
void RNA_property_collection_end(CollectionPropertyIterator *iter)
PyObject * pyrna_callback_classmethod_add(PyObject *, PyObject *args)
int CTX_data_get(const bContext *C, const char *member, PointerRNA *r_ptr, Vector< PointerRNA > *r_lb, PropertyRNA **r_prop, int *r_index, StringRef *r_str, std::optional< int64_t > *r_int_value, ContextDataType *r_type)
bool RNA_property_is_set_ex(PointerRNA *ptr, PropertyRNA *prop, bool use_ghost)
static PyObject * pyrna_prop_path_from_id(BPy_PropertyRNA *self)
Definition bpy_rna.cc:4393
void RNA_property_enum_items_ex(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const bool use_static, const EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
IDProperty * RNA_struct_idprops(PointerRNA *ptr, bool create)
PyMethodDef meth_bpy_register_class
Definition bpy_rna.cc:10547
static PyObject * pyrna_struct_get_data(BPy_DummyPointerRNA *self, void *)
Definition bpy_rna.cc:5540
static int pyrna_prop_compare(BPy_PropertyRNA *a, BPy_PropertyRNA *b)
Definition bpy_rna.cc:1002
bool(*)(Main *bmain, StructRNA *type) StructUnregisterFunc
static int prop_subscript_ass_array_slice__bool_recursive(PyObject **value_items, bool *value, int totdim, const int dimsize[])
Definition bpy_rna.cc:3221
static PyObject * pyrna_struct_get_id_data(BPy_DummyPointerRNA *self, void *)
Definition bpy_rna.cc:5523
std::string RNA_path_full_ID_py(ID *id)
Definition rna_path.cc:1290
wmWindowManager * CTX_wm_manager(const bContext *C)
static PyObject * pyrna_struct_values(BPy_StructRNA *self)
Definition bpy_rna.cc:3858
static int bpy_class_validate(PointerRNA *dummy_ptr, void *py_data, bool *have_function)
Definition bpy_rna.cc:9953
@ PROP_RAW_UINT8
Definition RNA_types.hh:716
@ PROP_RAW_DOUBLE
Definition RNA_types.hh:714
@ PROP_RAW_INT8
Definition RNA_types.hh:720
@ PROP_RAW_UINT16
Definition RNA_types.hh:717
@ PROP_RAW_INT
Definition RNA_types.hh:710
@ PROP_RAW_UINT64
Definition RNA_types.hh:719
@ PROP_RAW_SHORT
Definition RNA_types.hh:711
@ PROP_RAW_FLOAT
Definition RNA_types.hh:715
@ PROP_RAW_INT64
Definition RNA_types.hh:718
@ PROP_RAW_BOOLEAN
Definition RNA_types.hh:713
@ PROP_RAW_UNSET
Definition RNA_types.hh:709
@ PROP_RAW_CHAR
Definition RNA_types.hh:712
static int mathutils_rna_matrix_set(BaseMathObject *bmo, int)
Definition bpy_rna.cc:751
PyTypeObject BPy_IDGroup_Type
std::string RNA_function_as_string_keywords(bContext *C, FunctionRNA *func, const bool as_function, const bool all_args, const int max_prop_length)
static PyObject * pyrna_struct_property_unset(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:3932
static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
Definition bpy_rna.cc:4685
void PyC_ObSpit(const char *name, PyObject *var)
int pyrna_py_to_array_index(PointerRNA *ptr, PropertyRNA *prop, int arraydim, int arrayoffset, int index, PyObject *py, const char *error_prefix)
PyObject * Vector_CreatePyObject_cb(PyObject *cb_user, int vec_num, uchar cb_type, uchar cb_subtype)
static PyObject * pyrna_struct_id_properties_clear(BPy_StructRNA *self)
Definition bpy_rna.cc:4855
void pyrna_struct_type_extend_capi(StructRNA *srna, PyMethodDef *method, PyGetSetDef *getset)
Definition bpy_rna.cc:10943
unsigned char uint8_t
Definition BKE_text.h:79
static uchar mathutils_rna_array_cb_index
Definition bpy_rna.cc:584
int16_t PyC_Long_AsI16(PyObject *value)
PyObject * bpy_intern_str_attr
void RNA_property_unset(PointerRNA *ptr, PropertyRNA *prop)
static PyMethodDef pyrna_prop_collection_idprop_methods[]
Definition bpy_rna.cc:6828
static PyObject * pyrna_prop_collection_foreach_get(BPy_PropertyRNA *self, PyObject *args)
Definition bpy_rna.cc:6358
PyObject * pyrna_array_index(PointerRNA *ptr, PropertyRNA *prop, int index)
static int pyrna_struct_setattro(BPy_StructRNA *self, PyObject *pyname, PyObject *value)
Definition bpy_rna.cc:5169
bool pyrna_id_FromPyObject(PyObject *obj, ID **id)
Definition bpy_rna.cc:8988
int RNA_property_flag(PropertyRNA *prop)
static PySequenceMethods pyrna_prop_collection_as_sequence
Definition bpy_rna.cc:3692
int RNA_property_float_clamp(PointerRNA *ptr, PropertyRNA *prop, float *value)
PyObject * pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
Definition bpy_rna.cc:827
bool RNA_property_collection_lookup_string(PointerRNA *ptr, PropertyRNA *prop, const char *key, PointerRNA *r_ptr)
PyObject * bpy_intern_str_unregister
const char * RNA_function_identifier(FunctionRNA *func)
static PyObject * pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
Definition bpy_rna.cc:1010
static PyObject * pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
Definition bpy_rna.cc:2893
static PyObject * pyrna_struct_keys(BPy_StructRNA *self)
Definition bpy_rna.cc:3808
PyObject * bpy_intern_str_register
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
PyObject * Color_CreatePyObject(const float col[3], PyTypeObject *base_type)
static PySequenceMethods pyrna_prop_array_as_sequence
Definition bpy_rna.cc:3678
char pyrna_struct_driver_remove_doc[]
GHash * BLI_ghash_ptr_new(const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT
CLG_LogRef * BPY_LOG_RNA
Definition bpy.hh:29
PyTypeObject pyrna_prop_collection_Type
Definition bpy_rna.cc:7897
uchar Mathutils_RegisterCallback(Mathutils_Callback *cb)
Definition mathutils.cc:543
static int prop_subscript_ass_array_slice__int_recursive(PyObject **value_items, int *value, int totdim, const int dimsize[], const int range[2])
Definition bpy_rna.cc:3189
PyObject * BPY_rna_types()
Definition bpy_rna.cc:9246
RawPropertyType RNA_property_raw_type(PropertyRNA *prop)
bool RNA_property_is_idprop(const PropertyRNA *prop)
void RNA_struct_py_type_set(StructRNA *srna, void *py_type)
PyObject * BPy_IDGroup_WrapData(ID *id, IDProperty *prop, IDProperty *parent)
PointerRNA RNA_pointer_create_discrete(ID *id, StructRNA *type, void *data)
PropertyRNA * RNA_struct_type_find_property(StructRNA *srna, const char *identifier)
static void pyrna_dir_members_py(PyObject *list, PyObject *self)
Definition bpy_rna.cc:4653
const char * BKE_idtype_idcode_to_name_plural(short idcode)
Definition idtype.cc:268
static void pyrna_prop_collection_iter_dealloc(PyObject *self)
Definition bpy_rna.cc:8323
char * BLI_dynstr_get_cstring(const DynStr *ds) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_NONNULL()
static PyObject * pyrna_struct_is_property_readonly(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:4008
static PyObject * pyrna_struct_items(BPy_StructRNA *self)
Definition bpy_rna.cc:3833
static int pyrna_prop_collection_iter_init(PyObject *self, PyObject *, PyObject *)
Definition bpy_rna.cc:8278
static PyObject * pyrna_struct_bl_rna_get_subclass(PyObject *cls, PyObject *args)
Definition bpy_rna.cc:4571
static int pyrna_struct_meta_idprop_setattro(PyObject *cls, PyObject *attr, PyObject *value)
Definition bpy_rna.cc:5105
static int pyrna_property_array_init(PyObject *self, PyObject *args, PyObject *)
Definition bpy_rna.cc:8121
bool RNA_property_update_check(PropertyRNA *prop)
PyObject * pyrna_py_from_array(PointerRNA *ptr, PropertyRNA *prop)
void pyrna_struct_validity_exception_only(const BPy_StructRNA *pysrna)
Definition bpy_rna.cc:184
static PyObject * pyrna_prop_collection_idprop_remove(BPy_PropertyRNA *self, PyObject *value)
Definition bpy_rna.cc:5432
static void pyrna_prop_collection_string_subscript_unsupported_error(BPy_PropertyRNA *self, const char *error_prefix)
Definition bpy_rna.cc:2443
unsigned int BLI_ghash_len(const GHash *gh) ATTR_WARN_UNUSED_RESULT
Definition BLI_ghash.cc:706
static short pyrna_rotation_euler_order_get(PointerRNA *ptr, const short order_fallback, PropertyRNA **r_prop_eul_order)
Definition bpy_rna.cc:792
static PyObject * pyrna_struct_bl_rna_get_subclass_py(PyObject *cls, PyObject *args)
Definition bpy_rna.cc:4538
void RNA_property_collection_skip(CollectionPropertyIterator *iter, int num)
bool RNA_enum_id_from_value(const EnumPropertyItem *item, int value, const char **r_identifier)
uint64_t PyC_Long_AsU64(PyObject *value)
PropertyRNA * RNA_struct_name_property(const StructRNA *type)
const EnumPropertyItem rna_enum_dummy_NULL_items[]
Definition rna_rna.cc:28
static PyObject * pyrna_srna_Subtype(StructRNA *srna)
Definition bpy_rna.cc:8674
void BLI_ghashIterator_init(GHashIterator *ghi, GHash *gh)
Definition BLI_ghash.cc:901
bool RNA_property_collection_lookup_int_has_fn(PropertyRNA *prop)
static int mathutils_rna_generic_check(BaseMathObject *bmo)
Definition bpy_rna.cc:592
int RNA_property_array_dimension(const PointerRNA *ptr, PropertyRNA *prop, int length[])
int RNA_parameter_list_arg_count(const ParameterList *parms)
static PyObject * pyrna_prop_array_getattro(BPy_PropertyRNA *self, PyObject *pyname)
Definition bpy_rna.cc:5273
static PyObject * pyrna_property_new(PyTypeObject *type, PyObject *args, PyObject *)
Definition bpy_rna.cc:8010
static PyObject * pyrna_func_CreatePyObject(const PointerRNA *ptr, FunctionRNA *func)
Definition bpy_rna.cc:8484
static PyTypeObject * bpy_class_check_any_subclasses_registered(PyTypeObject *cls)
Definition bpy_rna.cc:10404
void BLI_str_tolower_ascii(char *str, size_t len) ATTR_NONNULL(1)
PyObject * pyrna_callback_classmethod_remove(PyObject *, PyObject *args)
static PyObject * foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
Definition bpy_rna.cc:6127
uint8_t PyC_Long_AsU8(PyObject *value)
void CTX_rna_disallow_write_set_p(bContext *C, const bool *rna_disallow_writes)
bool RNA_struct_is_ID(const StructRNA *type)
static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix, PyObject **r_value_coerce)
Definition bpy_rna.cc:1688
PyObject * PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format,...)
const char * PyC_UnicodeAsBytes(PyObject *py_str, PyObject **r_coerce)
static PyObject * pyrna_bl_owner_id_set(PyObject *, PyObject *value)
Definition bpy_rna.cc:11000
const DeprecatedRNA * RNA_property_deprecated(const PropertyRNA *prop)
PyObject * pyrna_struct_driver_remove(BPy_StructRNA *self, PyObject *args)
static int pyrna_prop_collection_string_subscript_supported_or_error(BPy_PropertyRNA *self, const char *error_prefix)
Definition bpy_rna.cc:2453
bool RNA_struct_system_idprops_register_check(const StructRNA *type)
const char * RNA_struct_identifier(const StructRNA *type)
static PyObject * pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
Definition bpy_rna.cc:2297
static PyObject * pyrna_prop_collection_idprop_move(BPy_PropertyRNA *self, PyObject *args)
Definition bpy_rna.cc:5486
static PyGetSetDef pyrna_func_getseters[]
Definition bpy_rna.cc:5591
int PyC_Long_AsBool(PyObject *value)
PyObject * BPy_Wrap_GetValues_View_WithID(ID *id, IDProperty *prop)
int pyrna_deferred_register_class(StructRNA *srna, PyTypeObject *py_class)
Definition bpy_rna.cc:9663
void RNA_struct_state_owner_set(const char *name)
void RNA_property_collection_next(CollectionPropertyIterator *iter)
float RNA_property_float_get(PointerRNA *ptr, PropertyRNA *prop)
static PyObject * pyrna_prop_update(BPy_PropertyRNA *self)
Definition bpy_rna.cc:4457
PropertySubType RNA_property_subtype(PropertyRNA *prop)
const char * RNA_struct_ui_description(const StructRNA *type)
static void pyrna_property_dealloc(PyObject *self)
Definition bpy_rna.cc:8100
bool RNA_property_collection_is_empty(PointerRNA *ptr, PropertyRNA *prop)
const PointerRNA * pyrna_struct_as_ptr(PyObject *py_obj, const StructRNA *srna)
Definition bpy_rna.cc:9391
static int pyrna_srna_contains_pointer_prop_srna(StructRNA *srna_props, StructRNA *srna, const char **r_prop_identifier)
Definition bpy_rna.cc:10761
void pyrna_write_set(bool val)
Definition bpy_rna.cc:522
static PyObject * pyrna_srna_PyBase(StructRNA *srna)
Definition bpy_rna.cc:8587
int RNA_parameter_flag(PropertyRNA *prop)
static PyObject * pyrna_struct_id_properties_ensure(BPy_StructRNA *self)
Definition bpy_rna.cc:4773
const StructRNA * RNA_struct_base_child_of(const StructRNA *type, const StructRNA *parent_type)
StructRNA * pyrna_struct_as_srna(PyObject *self, const bool parent, const char *error_prefix)
Definition bpy_rna.cc:9338
void pyrna_invalidate(BPy_DummyPointerRNA *self)
Definition bpy_rna.cc:211
static PyObject * pyrna_struct_Subtype(PointerRNA *ptr)
Definition bpy_rna.cc:8793
static const char * pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
Definition bpy_rna.cc:1366
T * DEG_get_original(T *id)
static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
Definition bpy_rna.cc:601
static PyObject * bpy_types_module_getattro(PyObject *self, PyObject *pyname)
Definition bpy_rna.cc:9134
PyTypeObject BPy_IDPropertyUIManager_Type
StructRNA *(*)(Main *bmain, ReportList *reports, void *data, const char *identifier, StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free) StructRegisterFunc
PyObject * pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
static int pyrna_prop_collection_subscript_str_lib_pair_ptr(BPy_PropertyRNA *self, PyObject *key, const char *err_prefix, const short err_not_found, PointerRNA *r_ptr)
Definition bpy_rna.cc:2651
uint16_t PyC_Long_AsU16(PyObject *value)
Main * CTX_data_main(const bContext *C)
char pyrna_struct_driver_add_doc[]
static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
Definition bpy_rna.cc:3756
int RNA_property_collection_raw_set(ReportList *reports, PointerRNA *ptr, PropertyRNA *prop, const char *propname, void *array, RawPropertyType type, int len)
static PyObject * pyprop_array_foreach_getset(BPy_PropertyArrayRNA *self, PyObject *args, const bool do_set)
Definition bpy_rna.cc:6387
static PyObject * pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
Definition bpy_rna.cc:1042
bool bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate) ATTR_NONNULL(1)
void IDP_FreeProperty(IDProperty *prop)
Definition idprop.cc:1403
static PyMappingMethods pyrna_prop_array_as_mapping
Definition bpy_rna.cc:3553
static PyObject * pyrna_prop_as_bytes(BPy_PropertyRNA *self)
Definition bpy_rna.cc:4420
StructRNA * RNA_struct_base(StructRNA *type)
static PyObject * pyrna_prop_array_foreach_set(BPy_PropertyArrayRNA *self, PyObject *args)
Definition bpy_rna.cc:6573
PyObject * pyrna_struct_CreatePyObject_with_primitive_support(PointerRNA *ptr)
Definition bpy_rna.cc:8910
static const char * BPy_PropertyPointerRNA_capsule_identifier
Definition bpy_rna.cc:118
char * RNA_struct_name_get_alloc_ex(PointerRNA *ptr, char *fixedbuf, int fixedlen, int *r_len, PropertyRNA **r_nameprop)
bool BLI_path_is_rel(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
static PyObject * pyrna_struct_repr(BPy_StructRNA *self)
Definition bpy_rna.cc:1111
static PyObject * pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:5694
void RNA_property_collection_clear(PointerRNA *ptr, PropertyRNA *prop)
std::optional< PointerRNA > RNA_property_collection_type_get(PointerRNA *ptr, PropertyRNA *prop)
static int pyrna_prop_collection_setattro(BPy_PropertyRNA *self, PyObject *pyname, PyObject *value)
Definition bpy_rna.cc:5358
static PyObject * pyrna_prop_repr(BPy_PropertyRNA *self)
Definition bpy_rna.cc:1286
static PyObject * pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
Definition bpy_rna.cc:3721
std::optional< std::string > RNA_path_full_property_py_ex(const PointerRNA *ptr, PropertyRNA *prop, int index, bool use_fallback)
Definition rna_path.cc:1341
void PyC_FileAndNum(const char **r_filename, int *r_lineno)
static PyObject * pyrna_prop_collection_iter_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop)
Definition bpy_rna.cc:8348
int RNA_function_call(bContext *C, ReportList *reports, PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
bool BLI_ghash_remove(GHash *gh, const void *key, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp)
Definition BLI_ghash.cc:792
static PyObject * pyrna_prop_array_foreach_get(BPy_PropertyArrayRNA *self, PyObject *args)
Definition bpy_rna.cc:6557
@ PROP_ENUM_FLAG
Definition RNA_types.hh:474
@ PROP_DYNAMIC
Definition RNA_types.hh:498
@ PROP_THICK_WRAP
Definition RNA_types.hh:493
@ PROP_IDPROPERTY
Definition RNA_types.hh:496
@ PROP_REGISTER_OPTIONAL
Definition RNA_types.hh:482
@ PROP_REGISTER
Definition RNA_types.hh:481
@ PROP_PATH_SUPPORTS_BLEND_RELATIVE
Definition RNA_types.hh:526
@ PROP_ID_SELF_CHECK
Definition RNA_types.hh:440
@ PROP_NEVER_NULL
Definition RNA_types.hh:447
@ PROP_HIDDEN
Definition RNA_types.hh:408
static PointerRNA * rna_module_ptr
Definition bpy_rna.cc:9080
static PyObject * pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
Definition bpy_rna.cc:3096
@ ID_TAG_TEMP_MAIN
Definition DNA_ID.h:974
static void pyrna_func_dealloc(PyObject *self)
Definition bpy_rna.cc:8504
void BPY_free_srna_pytype(StructRNA *srna)
Definition bpy_rna.cc:10480
static PyObject * pyrna_func_doc_get(BPy_FunctionRNA *self, void *closure)
Definition bpy_rna.cc:7439
bool RNA_property_collection_lookup_string_supported(PropertyRNA *prop)
void RNA_property_enum_set(PointerRNA *ptr, PropertyRNA *prop, int value)
StructRNA * srna_from_self(PyObject *self, const char *error_prefix)
Definition bpy_rna.cc:9438
static PyObject * pyrna_struct_CreatePyObject_from_type(const PointerRNA *ptr, PyTypeObject *tp, void **instance)
Definition bpy_rna.cc:8806
void pyrna_alloc_types()
Definition bpy_rna.cc:10448
const PointerRNA * pyrna_struct_as_ptr_or_null(PyObject *py_obj, const StructRNA *srna)
Definition bpy_rna.cc:9405
bool RNA_property_collection_lookup_int(PointerRNA *ptr, PropertyRNA *prop, int key, PointerRNA *r_ptr)
static StructRNA * srna_from_ptr(PointerRNA *ptr)
Definition bpy_rna.cc:8781
bool pyrna_write_check()
Definition bpy_rna.cc:515
bool RNA_property_collection_lookup_string_has_nameprop(PropertyRNA *prop)
bool RNA_property_editable(const PointerRNA *ptr, PropertyRNA *prop)
static void bpy_class_free_ex(PyObject *self, bool decref)
Definition bpy_rna.cc:10317
static PyObject * pyrna_struct_get_ancestors(BPy_StructRNA *self)
Definition bpy_rna.cc:4626
Span< std::unique_ptr< FunctionRNA > > RNA_struct_type_functions(StructRNA *srna)
static PyObject * pyrna_prop_path_from_module(BPy_PropertyRNA *self)
Definition bpy_rna.cc:4291
int RNA_property_int_clamp(PointerRNA *ptr, PropertyRNA *prop, int *value)
PyObject * PyC_UnicodeFromStdStr(const std::string &str)
static PyObject * pyrna_prop_collection_find(BPy_PropertyRNA *self, PyObject *key_ob)
Definition bpy_rna.cc:5892
static int pyrna_deferred_register_class_recursive(StructRNA *srna, PyTypeObject *py_class)
Definition bpy_rna.cc:9627
int RNA_property_multi_array_length(PointerRNA *ptr, PropertyRNA *prop, int dimension)
void RNA_property_boolean_set(PointerRNA *ptr, PropertyRNA *prop, bool value)
@ ID_FLAG_EMBEDDED_DATA
Definition DNA_ID.h:775
static PyObject * kwnames_get_item_string(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames, Py_ssize_t nkw, const char *parm_name)
Definition bpy_rna.cc:7040
bool RNA_path_resolve_full_maybe_null(const PointerRNA *ptr, const char *path, PointerRNA *r_ptr, PropertyRNA **r_prop, int *r_index)
Definition rna_path.cc:565
int RNA_def_property_free_identifier(StructOrFunctionRNA *cont_, const char *identifier)
static PyObject * pyrna_struct_dir(BPy_StructRNA *self)
Definition bpy_rna.cc:4726
PyObject * Color_CreatePyObject_cb(PyObject *cb_user, uchar cb_type, uchar cb_subtype)
static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
Definition bpy_rna.cc:2396
PyObject * bpy_intern_str_properties
static int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
Definition bpy_rna.cc:9603
ListBaseT< LinkData > CTX_data_dir_get(const bContext *C)
static PyMethodDef pyrna_prop_methods[]
Definition bpy_rna.cc:6760
void RNA_property_int_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, int value)
size_t RNA_raw_type_sizeof(RawPropertyType type)
void RNA_property_float_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, float value)
PyTypeObject pyrna_struct_Type
Definition bpy_rna.cc:7546
PyObject * PyC_ExceptionBuffer()
short BPy_reports_to_error(ReportList *reports, PyObject *exception, const bool clear)
PyTypeObject pyrna_prop_array_Type
Definition bpy_rna.cc:7841
@ CTX_RESULT_MEMBER_NOT_FOUND
@ CTX_RESULT_NO_DATA
void RNA_parameter_list_begin(ParameterList *parms, ParameterIterator *iter)
static PyObject * pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
Definition bpy_rna.cc:2756
PyObject * PyC_UnicodeFromBytesAndSize(const char *str, Py_ssize_t size)
static PyObject * pyrna_unregister_class(PyObject *self, PyObject *py_class)
Definition bpy_rna.cc:10814
static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
Definition bpy_rna.cc:2303
static PyObject * pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum)
Definition bpy_rna.cc:2560
@ RPT_PRINT_HANDLED_BY_OWNER
Definition BKE_report.hh:62
void RNA_property_boolean_set_index(PointerRNA *ptr, PropertyRNA *prop, int index, bool value)
void PyC_ObSpitStr(char *result, size_t result_maxncpy, PyObject *var)
@ PROP_FILENAME
Definition RNA_types.hh:286
@ PROP_MATRIX
Definition RNA_types.hh:322
@ PROP_BYTESTRING
Definition RNA_types.hh:295
@ PROP_FILEPATH
Definition RNA_types.hh:284
@ PROP_QUATERNION
Definition RNA_types.hh:324
@ PROP_DIRPATH
Definition RNA_types.hh:285
@ PROP_COLOR_GAMMA
Definition RNA_types.hh:329
@ PROP_UNSIGNED
Definition RNA_types.hh:306
@ PARM_REQUIRED
Definition RNA_types.hh:631
@ PARM_PYFUNC_REGISTER_OPTIONAL
Definition RNA_types.hh:643
@ PARM_RNAPTR
Definition RNA_types.hh:633
@ PARM_OUTPUT
Definition RNA_types.hh:632
char * pyrna_enum_repr(const EnumPropertyItem *item)
static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
Definition bpy_rna.cc:9959
ReportList * CTX_wm_reports(const bContext *C)
static int pyrna_struct_init(PyObject *self, PyObject *args, PyObject *)
Definition bpy_rna.cc:7656
int pyrna_py_to_array(PointerRNA *ptr, PropertyRNA *prop, char *param_data, PyObject *py, const char *error_prefix)
static PyObject * pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
Definition bpy_rna.cc:4333
int8_t PyC_Long_AsI8(PyObject *value)
int RNA_property_string_maxlength(PropertyRNA *prop)
int RNA_property_int_get(PointerRNA *ptr, PropertyRNA *prop)
static PyObject * pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args, PyObject *kw)
Definition bpy_rna.cc:3891
IDProperty ** RNA_struct_idprops_p(PointerRNA *ptr)
void RNA_property_int_range(PointerRNA *ptr, PropertyRNA *prop, int *hardmin, int *hardmax)
void bpy_context_clear(struct bContext *C, const PyGILState_STATE *gilstate)
void RNA_def_struct_name_property(StructRNA *srna, PropertyRNA *prop, const bool allow_replace)
void BPY_rna_init()
Definition bpy_rna.cc:9005
DynStr * BLI_dynstr_new() ATTR_MALLOC ATTR_WARN_UNUSED_RESULT
Definition BLI_dynstr.cc:39
static PyObject * pyweakref_get_ref(PyObject *ref)
Definition bpy_rna.cc:153
static PyObject * pyrna_struct_get_nameprop_as_pyobject(PointerRNA *ptr, BPy_NamePropAsPyObject_Cache &nameprop_cache)
Definition bpy_rna.cc:421
static PyObject * pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
Definition bpy_rna.cc:6856
BLI_INLINE bool BLI_ghashIterator_done(const GHashIterator *ghi) ATTR_WARN_UNUSED_RESULT
Definition BLI_ghash.hh:309
static bool foreach_attr_type(BPy_PropertyRNA *self, const char *attr, RawPropertyType *r_raw_type, int *r_attr_tot, bool *r_attr_signed, bool *r_is_empty)
Definition bpy_rna.cc:5926
bool IDP_ui_data_supported(const IDProperty *prop)
Definition idprop.cc:1986
PyMethodDef meth_bpy_owner_id_get
Definition bpy_rna.cc:11030
static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
Definition bpy_rna.cc:3617
int pyrna_struct_validity_check_only(const BPy_StructRNA *pysrna)
Definition bpy_rna.cc:176
static bool pyrna_status_ok_or_error(eRNAStatus status, const char *error_prefix)
Definition bpy_rna.cc:230
static Py_hash_t pyrna_struct_hash(BPy_StructRNA *self)
Definition bpy_rna.cc:1305
static uchar mathutils_rna_matrix_cb_index
Definition bpy_rna.cc:735
static PyObject * pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
Definition bpy_rna.cc:2465
int pyrna_array_contains_py(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
static int pyrna_deferred_register_class_from_type_hints(StructRNA *srna, PyTypeObject *py_class)
Definition bpy_rna.cc:9547
static PyObject * pyrna_struct_bl_rna_find_subclass_recursive(PyObject *cls, const char *id)
Definition bpy_rna.cc:4485
static PyObject * pyrna_prop_dir(BPy_PropertyRNA *self)
Definition bpy_rna.cc:5250
signed char int8_t
Definition BKE_text.h:76
PyObject * Euler_CreatePyObject_cb(PyObject *cb_user, const short order, uchar cb_type, uchar cb_subtype)
const ListBaseT< PropertyRNA > * RNA_function_defined_parameters(FunctionRNA *func)
void RNA_parameter_list_free(ParameterList *parms)
static PyTypeObject pyrna_prop_collection_idprop_Type
Definition bpy_rna.cc:7954
PyObject * bpy_intern_str___module__
void RNA_property_float_range(PointerRNA *ptr, PropertyRNA *prop, float *hardmin, float *hardmax)
PyObject * bpy_intern_str_bl_rna
StructRegisterFunc RNA_struct_register(StructRNA *type)
static const char * BPy_capsule_PointerRNA_identifier
Definition bpy_rna.cc:106
static PyObject * pyrna_struct_type_recast(BPy_StructRNA *self)
Definition bpy_rna.cc:4473
void BPY_update_rna_module()
Definition bpy_rna.cc:9093
int BPy_Wrap_SetMapItem(IDProperty *prop, PyObject *key, PyObject *val)
static PyObject * pyrna_prop_collection_keys(BPy_PropertyRNA *self)
Definition bpy_rna.cc:5610
static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
Definition bpy_rna.cc:1414
header-only compatibility defines.
#define Py_HashPointer
header-only utilities
#define PyTuple_SET_ITEMS(op_arg,...)
#define min(a, b)
Definition sort.cc:38
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:124
vectorcallfunc vectorcall
Definition bpy_rna.hh:200
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:194
PyObject_HEAD IDProperty * property
struct IDProperty * parent
struct IDProperty * prop
PyObject_HEAD struct ID * owner_id
PyObject *(*) nameprop_as_py_object_fn(const char *, Py_ssize_t)
Definition bpy_rna.cc:414
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:166
PyObject_HEAD std::optional< CollectionPropertyIterator > iter
Definition bpy_rna.hh:185
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:153
const PointerRNA * ptr
Definition bpy_rna.hh:250
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:133
std::optional< PointerRNA > ptr
Definition bpy_rna.cc:9129
Vector< PointerRNA > items
Definition RNA_types.hh:705
char name[258]
Definition DNA_ID.h:433
ListBaseT< Library > libraries
Definition BKE_main.hh:387
bool has_type() const
Definition RNA_types.hh:180
StructRNA * type
Definition RNA_types.hh:63
ListBaseT< Report > list
Definition BKE_report.hh:79
Defines a node type.
Definition BKE_node.hh:265
struct ReportList * reports