1f35572a483fce284d3534a8db1cee7a27bd6ea4
[blender-staging.git] / source / blender / python / generic / idprop_py_api.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  *
19  * Contributor(s): Joseph Eagar, Campbell Barton
20  *
21  * ***** END GPL LICENSE BLOCK *****
22  */
23
24 /** \file blender/python/generic/idprop_py_api.c
25  *  \ingroup pygen
26  */
27
28 #include <Python.h>
29
30 #include "MEM_guardedalloc.h"
31
32 #include "BLI_utildefines.h"
33
34 #include "idprop_py_api.h"
35
36 #include "BKE_idprop.h"
37
38 #define USE_STRING_COERCE
39
40 #ifdef USE_STRING_COERCE
41 #include "py_capi_utils.h"
42 #endif
43
44 #include "../generic/python_utildefines.h"
45
46
47 /*********************** ID Property Main Wrapper Stuff ***************/
48
49 /* ----------------------------------------------------------------------------
50  * static conversion functions to avoid duplicate code, no type checking.
51  */
52
53 static PyObject *idprop_py_from_idp_string(const IDProperty *prop)
54 {
55         if (prop->subtype == IDP_STRING_SUB_BYTE) {
56                 return PyBytes_FromStringAndSize(IDP_String(prop), prop->len);
57         }
58         else {
59 #ifdef USE_STRING_COERCE
60                 return PyC_UnicodeFromByteAndSize(IDP_Array(prop), prop->len - 1);
61 #else
62                 return PyUnicode_FromStringAndSize(IDP_String(prop), prop->len - 1);
63 #endif
64         }
65 }
66
67 static PyObject *idprop_py_from_idp_int(const IDProperty *prop)
68 {
69         return PyLong_FromLong((long)IDP_Int(prop));
70 }
71
72 static PyObject *idprop_py_from_idp_float(const IDProperty *prop)
73 {
74         return PyFloat_FromDouble((double)IDP_Float(prop));
75 }
76
77 static PyObject *idprop_py_from_idp_double(const IDProperty *prop)
78 {
79         return PyFloat_FromDouble(IDP_Double(prop));
80 }
81
82 static PyObject *idprop_py_from_idp_group(ID *id, IDProperty *prop, IDProperty *parent)
83 {
84         BPy_IDProperty *group = PyObject_New(BPy_IDProperty, &BPy_IDGroup_Type);
85         group->id = id;
86         group->prop = prop;
87         group->parent = parent; /* can be NULL */
88         return (PyObject *)group;
89 }
90
91 static PyObject *idprop_py_from_idp_array(ID *id, IDProperty *prop)
92 {
93         BPy_IDProperty *array = PyObject_New(BPy_IDProperty, &BPy_IDArray_Type);
94         array->id = id;
95         array->prop = prop;
96         return (PyObject *)array;
97 }
98
99 static PyObject *idprop_py_from_idp_idparray(ID *id, IDProperty *prop)
100 {
101         PyObject *seq = PyList_New(prop->len), *wrap;
102         IDProperty *array = IDP_IDPArray(prop);
103         int i;
104
105         if (!seq) {
106                 PyErr_Format(PyExc_RuntimeError,
107                              "%s: IDP_IDPARRAY: PyList_New(%d) failed",
108                              __func__, prop->len);
109                 return NULL;
110         }
111
112         for (i = 0; i < prop->len; i++) {
113                 wrap = BPy_IDGroup_WrapData(id, array++, prop);
114
115                 if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
116                         return NULL;
117
118                 PyList_SET_ITEM(seq, i, wrap);
119         }
120
121         return seq;
122 }
123
124 /* -------------------------------------------------------------------------- */
125
126 /* use for both array and group */
127 static Py_hash_t BPy_IDGroup_hash(BPy_IDProperty *self)
128 {
129         return _Py_HashPointer(self->prop);
130 }
131
132 static PyObject *BPy_IDGroup_repr(BPy_IDProperty *self)
133 {
134         return PyUnicode_FromFormat("<bpy id prop: owner=\"%s\", name=\"%s\", address=%p>",
135                                     self->id ? self->id->name : "<NONE>", self->prop->name, self->prop);
136 }
137
138 PyObject *BPy_IDGroup_WrapData(ID *id, IDProperty *prop, IDProperty *parent)
139 {
140         switch (prop->type) {
141                 case IDP_STRING:   return idprop_py_from_idp_string(prop);
142                 case IDP_INT:      return idprop_py_from_idp_int(prop);
143                 case IDP_FLOAT:    return idprop_py_from_idp_float(prop);
144                 case IDP_DOUBLE:   return idprop_py_from_idp_double(prop);
145                 case IDP_GROUP:    return idprop_py_from_idp_group(id, prop, parent);
146                 case IDP_ARRAY:    return idprop_py_from_idp_array(id, prop);
147                 case IDP_IDPARRAY: return idprop_py_from_idp_idparray(id, prop); /* this could be better a internal type */
148                 default: Py_RETURN_NONE;
149         }
150 }
151
152 #if 0 /* UNUSED, currently assignment overwrites into new properties, rather than setting in-place */
153 static int BPy_IDGroup_SetData(BPy_IDProperty *self, IDProperty *prop, PyObject *value)
154 {
155         switch (prop->type) {
156                 case IDP_STRING:
157                 {
158                         char *st;
159                         if (!PyUnicode_Check(value)) {
160                                 PyErr_SetString(PyExc_TypeError, "expected a string!");
161                                 return -1;
162                         }
163                         /* NOTE: if this code is enabled, bytes support needs to be added */
164 #ifdef USE_STRING_COERCE
165                         {
166                                 int alloc_len;
167                                 PyObject *value_coerce = NULL;
168
169                                 st = (char *)PyC_UnicodeAsByte(value, &value_coerce);
170                                 alloc_len = strlen(st) + 1;
171
172                                 st = _PyUnicode_AsString(value);
173                                 IDP_ResizeArray(prop, alloc_len);
174                                 memcpy(IDP_Array(prop), st, alloc_len);
175                                 Py_XDECREF(value_coerce);
176                         }
177 #else
178                         st = _PyUnicode_AsString(value);
179                         IDP_ResizeArray(prop, strlen(st) + 1);
180                         strcpy(IDP_Array(prop), st);
181 #endif
182
183                         return 0;
184                 }
185
186                 case IDP_INT:
187                 {
188                         int ivalue = PyLong_AsSsize_t(value);
189                         if (ivalue == -1 && PyErr_Occurred()) {
190                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
191                                 return -1;
192                         }
193                         IDP_Int(prop) = ivalue;
194                         break;
195                 }
196                 case IDP_FLOAT:
197                 {
198                         float fvalue = (float)PyFloat_AsDouble(value);
199                         if (fvalue == -1 && PyErr_Occurred()) {
200                                 PyErr_SetString(PyExc_TypeError, "expected a float");
201                                 return -1;
202                         }
203                         IDP_Float(self->prop) = fvalue;
204                         break;
205                 }
206                 case IDP_DOUBLE:
207                 {
208                         double dvalue = PyFloat_AsDouble(value);
209                         if (dvalue == -1 && PyErr_Occurred()) {
210                                 PyErr_SetString(PyExc_TypeError, "expected a float");
211                                 return -1;
212                         }
213                         IDP_Double(self->prop) = dvalue;
214                         break;
215                 }
216                 default:
217                         PyErr_SetString(PyExc_AttributeError, "attempt to set read-only attribute!");
218                         return -1;
219         }
220         return 0;
221 }
222 #endif
223
224 static PyObject *BPy_IDGroup_GetName(BPy_IDProperty *self, void *UNUSED(closure))
225 {
226         return PyUnicode_FromString(self->prop->name);
227 }
228
229 static int BPy_IDGroup_SetName(BPy_IDProperty *self, PyObject *value, void *UNUSED(closure))
230 {
231         const char *name;
232         Py_ssize_t name_size;
233
234         if (!PyUnicode_Check(value)) {
235                 PyErr_SetString(PyExc_TypeError, "expected a string!");
236                 return -1;
237         }
238
239         name = _PyUnicode_AsStringAndSize(value, &name_size);
240
241         if (name_size > MAX_IDPROP_NAME) {
242                 PyErr_SetString(PyExc_TypeError, "string length cannot exceed 63 characters!");
243                 return -1;
244         }
245
246         memcpy(self->prop->name, name, name_size);
247         return 0;
248 }
249
250 #if 0
251 static PyObject *BPy_IDGroup_GetType(BPy_IDProperty *self)
252 {
253         return PyLong_FromLong(self->prop->type);
254 }
255 #endif
256
257 static PyGetSetDef BPy_IDGroup_getseters[] = {
258         {(char *)"name", (getter)BPy_IDGroup_GetName, (setter)BPy_IDGroup_SetName, (char *)"The name of this Group.", NULL},
259         {NULL, NULL, NULL, NULL, NULL}
260 };
261
262 static Py_ssize_t BPy_IDGroup_Map_Len(BPy_IDProperty *self)
263 {
264         if (self->prop->type != IDP_GROUP) {
265                 PyErr_SetString(PyExc_TypeError, "len() of unsized object");
266                 return -1;
267         }
268
269         return self->prop->len;
270 }
271
272 static PyObject *BPy_IDGroup_Map_GetItem(BPy_IDProperty *self, PyObject *item)
273 {
274         IDProperty *idprop;
275         const char *name;
276
277         if (self->prop->type != IDP_GROUP) {
278                 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
279                 return NULL;
280         }
281
282         name = _PyUnicode_AsString(item);
283
284         if (name == NULL) {
285                 PyErr_SetString(PyExc_TypeError, "only strings are allowed as keys of ID properties");
286                 return NULL;
287         }
288
289         idprop = IDP_GetPropertyFromGroup(self->prop, name);
290
291         if (idprop == NULL) {
292                 PyErr_SetString(PyExc_KeyError, "key not in subgroup dict");
293                 return NULL;
294         }
295
296         return BPy_IDGroup_WrapData(self->id, idprop, self->prop);
297 }
298
299 /* returns NULL on success, error string on failure */
300 static char idp_sequence_type(PyObject *seq_fast)
301 {
302         PyObject *item;
303         char type = IDP_INT;
304
305         Py_ssize_t i, len = PySequence_Fast_GET_SIZE(seq_fast);
306         for (i = 0; i < len; i++) {
307                 item = PySequence_Fast_GET_ITEM(seq_fast, i);
308                 if (PyFloat_Check(item)) {
309                         if (type == IDP_IDPARRAY) { /* mixed dict/int */
310                                 return -1;
311                         }
312                         type = IDP_DOUBLE;
313                 }
314                 else if (PyLong_Check(item)) {
315                         if (type == IDP_IDPARRAY) { /* mixed dict/int */
316                                 return -1;
317                         }
318                 }
319                 else if (PyMapping_Check(item)) {
320                         if (i != 0 && (type != IDP_IDPARRAY)) { /* mixed dict/int */
321                                 return -1;
322                         }
323                         type = IDP_IDPARRAY;
324                 }
325                 else {
326                         return -1;
327                 }
328         }
329
330         return type;
331 }
332
333 /**
334  * \note group can be a pointer array or a group.
335  * assume we already checked key is a string.
336  *
337  * \return success.
338  */
339 bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty *group, PyObject *ob)
340 {
341         IDProperty *prop = NULL;
342         IDPropertyTemplate val = {0};
343
344         const char *name;
345
346         if (name_obj) {
347                 Py_ssize_t name_size;
348                 name = _PyUnicode_AsStringAndSize(name_obj, &name_size);
349
350                 if (name == NULL) {
351                         PyErr_Format(PyExc_KeyError,
352                                      "invalid id-property key, expected a string, not a %.200s",
353                                      Py_TYPE(name_obj)->tp_name);
354                         return false;
355                 }
356
357                 if (name_size > MAX_IDPROP_NAME) {
358                         PyErr_SetString(PyExc_KeyError, "the length of IDProperty names is limited to 63 characters");
359                         return false;
360                 }
361         }
362         else {
363                 name = "";
364         }
365
366         if (PyFloat_Check(ob)) {
367                 val.d = PyFloat_AsDouble(ob);
368                 prop = IDP_New(IDP_DOUBLE, &val, name);
369         }
370         else if (PyLong_Check(ob)) {
371                 val.i = _PyLong_AsInt(ob);
372                 if (val.i == -1 && PyErr_Occurred()) {
373                         return false;
374                 }
375                 prop = IDP_New(IDP_INT, &val, name);
376         }
377         else if (PyUnicode_Check(ob)) {
378 #ifdef USE_STRING_COERCE
379                 PyObject *value_coerce = NULL;
380                 val.string.str = PyC_UnicodeAsByte(ob, &value_coerce);
381                 val.string.subtype = IDP_STRING_SUB_UTF8;
382                 prop = IDP_New(IDP_STRING, &val, name);
383                 Py_XDECREF(value_coerce);
384 #else
385                 val.str = _PyUnicode_AsString(ob);
386                 prop = IDP_New(IDP_STRING, val, name);
387 #endif
388         }
389         else if (PyBytes_Check(ob)) {
390                 val.string.str = PyBytes_AS_STRING(ob);
391                 val.string.len = PyBytes_GET_SIZE(ob);
392                 val.string.subtype = IDP_STRING_SUB_BYTE;
393
394                 prop = IDP_New(IDP_STRING, &val, name);
395                 //prop = IDP_NewString(PyBytes_AS_STRING(ob), name, PyBytes_GET_SIZE(ob));
396                 //prop->subtype = IDP_STRING_SUB_BYTE;
397         }
398         else if (PySequence_Check(ob)) {
399                 PyObject *ob_seq_fast = PySequence_Fast(ob, "py -> idprop");
400                 PyObject *item;
401                 int i;
402
403                 if (ob_seq_fast == NULL) {
404                         return false;
405                 }
406
407                 if ((val.array.type = idp_sequence_type(ob_seq_fast)) == (char)-1) {
408                         Py_DECREF(ob_seq_fast);
409                         PyErr_SetString(PyExc_TypeError, "only floats, ints and dicts are allowed in ID property arrays");
410                         return false;
411                 }
412
413                 /* validate sequence and derive type.
414                  * we assume IDP_INT unless we hit a float
415                  * number; then we assume it's */
416
417                 val.array.len = PySequence_Fast_GET_SIZE(ob_seq_fast);
418
419                 switch (val.array.type) {
420                         case IDP_DOUBLE:
421                         {
422                                 double *prop_data;
423
424                                 prop = IDP_New(IDP_ARRAY, &val, name);
425                                 prop_data = IDP_Array(prop);
426                                 for (i = 0; i < val.array.len; i++) {
427                                         item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
428                                         if (((prop_data[i] = PyFloat_AsDouble(item)) == -1.0) && PyErr_Occurred()) {
429                                                 Py_DECREF(ob_seq_fast);
430                                                 return false;
431                                         }
432                                 }
433                                 break;
434                         }
435                         case IDP_INT:
436                         {
437                                 int *prop_data;
438                                 prop = IDP_New(IDP_ARRAY, &val, name);
439                                 prop_data = IDP_Array(prop);
440                                 for (i = 0; i < val.array.len; i++) {
441                                         item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
442                                         if (((prop_data[i] = _PyLong_AsInt(item)) == -1) && PyErr_Occurred()) {
443                                                 Py_DECREF(ob_seq_fast);
444                                                 return false;
445                                         }
446                                 }
447                                 break;
448                         }
449                         case IDP_IDPARRAY:
450                         {
451                                 prop = IDP_NewIDPArray(name);
452                                 for (i = 0; i < val.array.len; i++) {
453                                         item = PySequence_Fast_GET_ITEM(ob_seq_fast, i);
454
455                                         if (BPy_IDProperty_Map_ValidateAndCreate(NULL, prop, item) == false) {
456                                                 Py_DECREF(ob_seq_fast);
457                                                 return false;
458                                         }
459                                 }
460                                 break;
461                         }
462                         default:
463                                 /* should never happen */
464                                 Py_DECREF(ob_seq_fast);
465                                 PyErr_SetString(PyExc_RuntimeError, "internal error with idp array.type");
466                                 return false;
467                 }
468
469                 Py_DECREF(ob_seq_fast);
470         }
471         else if (PyMapping_Check(ob)) {
472                 PyObject *keys, *vals, *key, *pval;
473                 int i, len;
474                 /*yay! we get into recursive stuff now!*/
475                 keys = PyMapping_Keys(ob);
476                 vals = PyMapping_Values(ob);
477
478                 /* we allocate the group first; if we hit any invalid data,
479                  * we can delete it easily enough.*/
480                 prop = IDP_New(IDP_GROUP, &val, name);
481                 len = PyMapping_Length(ob);
482                 for (i = 0; i < len; i++) {
483                         key = PySequence_GetItem(keys, i);
484                         pval = PySequence_GetItem(vals, i);
485                         if (BPy_IDProperty_Map_ValidateAndCreate(key, prop, pval) == false) {
486                                 IDP_FreeProperty(prop);
487                                 MEM_freeN(prop);
488                                 Py_XDECREF(keys);
489                                 Py_XDECREF(vals);
490                                 Py_XDECREF(key);
491                                 Py_XDECREF(pval);
492                                 /* error is already set */
493                                 return false;
494                         }
495                         Py_XDECREF(key);
496                         Py_XDECREF(pval);
497                 }
498                 Py_XDECREF(keys);
499                 Py_XDECREF(vals);
500         }
501         else {
502                 PyErr_Format(PyExc_TypeError,
503                              "invalid id-property type %.200s not supported",
504                              Py_TYPE(ob)->tp_name);
505                 return false;
506         }
507
508         if (group->type == IDP_IDPARRAY) {
509                 IDP_AppendArray(group, prop);
510                 // IDP_FreeProperty(item);  /* IDP_AppendArray does a shallow copy (memcpy), only free memory */
511                 MEM_freeN(prop);
512         }
513         else {
514                 IDProperty *prop_exist;
515
516                 /* avoid freeing when types match in case they are referenced by the UI, see: T37073
517                  * obviously this isn't a complete solution, but helps for common cases. */
518                 prop_exist = IDP_GetPropertyFromGroup(group, prop->name);
519                 if ((prop_exist != NULL) &&
520                     (prop_exist->type == prop->type) &&
521                     (prop_exist->subtype == prop->subtype))
522                 {
523                         /* Preserve prev/next links!!! See T42593. */
524                         prop->prev = prop_exist->prev;
525                         prop->next = prop_exist->next;
526
527                         IDP_FreeProperty(prop_exist);
528                         *prop_exist = *prop;
529                         MEM_freeN(prop);
530                 }
531                 else {
532                         IDP_ReplaceInGroup_ex(group, prop, prop_exist);
533                 }
534         }
535
536         return true;
537 }
538
539 int BPy_Wrap_SetMapItem(IDProperty *prop, PyObject *key, PyObject *val)
540 {
541         if (prop->type != IDP_GROUP) {
542                 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
543                 return -1;
544         }
545
546         if (val == NULL) { /* del idprop[key] */
547                 IDProperty *pkey;
548                 const char *name = _PyUnicode_AsString(key);
549
550                 if (name == NULL) {
551                         PyErr_Format(PyExc_KeyError,
552                                      "expected a string, not %.200s",
553                                      Py_TYPE(key)->tp_name);
554                         return -1;
555                 }
556
557                 pkey = IDP_GetPropertyFromGroup(prop, name);
558                 if (pkey) {
559                         IDP_FreeFromGroup(prop, pkey);
560                         return 0;
561                 }
562                 else {
563                         PyErr_SetString(PyExc_KeyError, "property not found in group");
564                         return -1;
565                 }
566         }
567         else {
568                 bool ok;
569
570                 ok = BPy_IDProperty_Map_ValidateAndCreate(key, prop, val);
571                 if (ok == false) {
572                         return -1;
573                 }
574
575                 return 0;
576         }
577 }
578
579 static int BPy_IDGroup_Map_SetItem(BPy_IDProperty *self, PyObject *key, PyObject *val)
580 {
581         return BPy_Wrap_SetMapItem(self->prop, key, val);
582 }
583
584 static PyObject *BPy_IDGroup_iter(BPy_IDProperty *self)
585 {
586         BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
587         iter->group = self;
588         iter->mode = IDPROP_ITER_KEYS;
589         iter->cur = self->prop->data.group.first;
590         Py_XINCREF(iter);
591         return (PyObject *)iter;
592 }
593
594 /* for simple, non nested types this is the same as BPy_IDGroup_WrapData */
595 static PyObject *BPy_IDGroup_MapDataToPy(IDProperty *prop)
596 {
597         switch (prop->type) {
598                 case IDP_STRING:
599                         return idprop_py_from_idp_string(prop);
600                 case IDP_INT:
601                         return idprop_py_from_idp_int(prop);
602                 case IDP_FLOAT:
603                         return idprop_py_from_idp_float(prop);
604                 case IDP_DOUBLE:
605                         return idprop_py_from_idp_double(prop);
606                 case IDP_ARRAY:
607                 {
608                         PyObject *seq = PyList_New(prop->len);
609                         int i;
610
611                         if (!seq) {
612                                 PyErr_Format(PyExc_RuntimeError,
613                                              "%s: IDP_ARRAY: PyList_New(%d) failed",
614                                              __func__, prop->len);
615                                 return NULL;
616                         }
617
618                         switch (prop->subtype) {
619                                 case IDP_FLOAT:
620                                 {
621                                         const float *array = (float *)IDP_Array(prop);
622                                         for (i = 0; i < prop->len; i++) {
623                                                 PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
624                                         }
625                                         break;
626                                 }
627                                 case IDP_DOUBLE:
628                                 {
629                                         const double *array = (double *)IDP_Array(prop);
630                                         for (i = 0; i < prop->len; i++) {
631                                                 PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
632                                         }
633                                         break;
634                                 }
635                                 case IDP_INT:
636                                 {
637                                         const int *array = (int *)IDP_Array(prop);
638                                         for (i = 0; i < prop->len; i++) {
639                                                 PyList_SET_ITEM(seq, i, PyLong_FromLong(array[i]));
640                                         }
641                                         break;
642                                 }
643                                 default:
644                                         PyErr_Format(PyExc_RuntimeError,
645                                                      "%s: invalid/corrupt array type '%d'!",
646                                                      __func__, prop->subtype);
647                                         Py_DECREF(seq);
648                                         return NULL;
649                         }
650
651                         return seq;
652                 }
653                 case IDP_IDPARRAY:
654                 {
655                         PyObject *seq = PyList_New(prop->len), *wrap;
656                         IDProperty *array = IDP_IDPArray(prop);
657                         int i;
658
659                         if (!seq) {
660                                 PyErr_Format(PyExc_RuntimeError,
661                                              "%s: IDP_IDPARRAY: PyList_New(%d) failed",
662                                              __func__, prop->len);
663                                 return NULL;
664                         }
665
666                         for (i = 0; i < prop->len; i++) {
667                                 wrap = BPy_IDGroup_MapDataToPy(array++);
668
669                                 if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
670                                         return NULL;
671
672                                 PyList_SET_ITEM(seq, i, wrap);
673                         }
674                         return seq;
675                 }
676                 case IDP_GROUP:
677                 {
678                         PyObject *dict = PyDict_New(), *wrap;
679                         IDProperty *loop;
680
681                         for (loop = prop->data.group.first; loop; loop = loop->next) {
682                                 wrap = BPy_IDGroup_MapDataToPy(loop);
683
684                                 if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
685                                         return NULL;
686
687                                 PyDict_SetItemString(dict, loop->name, wrap);
688                                 Py_DECREF(wrap);
689                         }
690                         return dict;
691                 }
692         }
693
694         PyErr_Format(PyExc_RuntimeError,
695                      "%s ERROR: '%s' property exists with a bad type code '%d'!",
696                      __func__, prop->name, prop->type);
697         return NULL;
698 }
699
700 static PyObject *BPy_IDGroup_Pop(BPy_IDProperty *self, PyObject *value)
701 {
702         IDProperty *idprop;
703         PyObject *pyform;
704         const char *name = _PyUnicode_AsString(value);
705
706         if (!name) {
707                 PyErr_Format(PyExc_TypeError,
708                              "pop expected at least a string argument, not %.200s",
709                              Py_TYPE(value)->tp_name);
710                 return NULL;
711         }
712
713         idprop = IDP_GetPropertyFromGroup(self->prop, name);
714
715         if (idprop) {
716                 pyform = BPy_IDGroup_MapDataToPy(idprop);
717
718                 if (!pyform) {
719                         /* ok something bad happened with the pyobject,
720                          * so don't remove the prop from the group.  if pyform is
721                          * NULL, then it already should have raised an exception.*/
722                         return NULL;
723                 }
724
725                 IDP_RemoveFromGroup(self->prop, idprop);
726                 return pyform;
727         }
728
729         PyErr_SetString(PyExc_KeyError, "item not in group");
730         return NULL;
731 }
732
733 static PyObject *BPy_IDGroup_IterItems(BPy_IDProperty *self)
734 {
735         BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
736         iter->group = self;
737         iter->mode = IDPROP_ITER_ITEMS;
738         iter->cur = self->prop->data.group.first;
739         Py_XINCREF(iter);
740         return (PyObject *)iter;
741 }
742
743 /* utility function */
744 static void BPy_IDGroup_CorrectListLen(IDProperty *prop, PyObject *seq, int len, const char *func)
745 {
746         int j;
747
748         printf("%s: ID Property Error found and corrected!\n", func);
749
750         /* fill rest of list with valid references to None */
751         for (j = len; j < prop->len; j++) {
752                 PyList_SET_ITEM(seq, j, Py_INCREF_RET(Py_None));
753         }
754
755         /*set correct group length*/
756         prop->len = len;
757 }
758
759 PyObject *BPy_Wrap_GetKeys(IDProperty *prop)
760 {
761         PyObject *list = PyList_New(prop->len);
762         IDProperty *loop;
763         int i;
764
765         for (i = 0, loop = prop->data.group.first; loop && (i < prop->len); loop = loop->next, i++)
766                 PyList_SET_ITEM(list, i, PyUnicode_FromString(loop->name));
767
768         /* if the id prop is corrupt, count the remaining */
769         for ( ; loop; loop = loop->next, i++) {
770                 /* pass */
771         }
772
773         if (i != prop->len) { /* if the loop didnt finish, we know the length is wrong */
774                 BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
775                 Py_DECREF(list); /*free the list*/
776                 /*call self again*/
777                 return BPy_Wrap_GetKeys(prop);
778         }
779
780         return list;
781 }
782
783 PyObject *BPy_Wrap_GetValues(ID *id, IDProperty *prop)
784 {
785         PyObject *list = PyList_New(prop->len);
786         IDProperty *loop;
787         int i;
788
789         for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
790                 PyList_SET_ITEM(list, i, BPy_IDGroup_WrapData(id, loop, prop));
791         }
792
793         if (i != prop->len) {
794                 BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
795                 Py_DECREF(list); /*free the list*/
796                 /*call self again*/
797                 return BPy_Wrap_GetValues(id, prop);
798         }
799
800         return list;
801 }
802
803 PyObject *BPy_Wrap_GetItems(ID *id, IDProperty *prop)
804 {
805         PyObject *seq = PyList_New(prop->len);
806         IDProperty *loop;
807         int i;
808
809         for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
810                 PyObject *item = PyTuple_New(2);
811                 PyTuple_SET_ITEMS(item,
812                         PyUnicode_FromString(loop->name),
813                         BPy_IDGroup_WrapData(id, loop, prop));
814                 PyList_SET_ITEM(seq, i, item);
815         }
816
817         if (i != prop->len) {
818                 BPy_IDGroup_CorrectListLen(prop, seq, i, __func__);
819                 Py_DECREF(seq); /*free the list*/
820                 /*call self again*/
821                 return BPy_Wrap_GetItems(id, prop);
822         }
823
824         return seq;
825 }
826
827
828 static PyObject *BPy_IDGroup_GetKeys(BPy_IDProperty *self)
829 {
830         return BPy_Wrap_GetKeys(self->prop);
831 }
832
833 static PyObject *BPy_IDGroup_GetValues(BPy_IDProperty *self)
834 {
835         return BPy_Wrap_GetValues(self->id, self->prop);
836 }
837
838 static PyObject *BPy_IDGroup_GetItems(BPy_IDProperty *self)
839 {
840         return BPy_Wrap_GetItems(self->id, self->prop);
841 }
842
843 static int BPy_IDGroup_Contains(BPy_IDProperty *self, PyObject *value)
844 {
845         const char *name = _PyUnicode_AsString(value);
846
847         if (!name) {
848                 PyErr_Format(PyExc_TypeError,
849                              "expected a string, not a %.200s",
850                              Py_TYPE(value)->tp_name);
851                 return -1;
852         }
853
854         return IDP_GetPropertyFromGroup(self->prop, name) ? 1 : 0;
855 }
856
857 static PyObject *BPy_IDGroup_Update(BPy_IDProperty *self, PyObject *value)
858 {
859         PyObject *pkey, *pval;
860         Py_ssize_t i = 0;
861
862         if (BPy_IDGroup_Check(value)) {
863                 BPy_IDProperty *other = (BPy_IDProperty *)value;
864                 if (UNLIKELY(self->prop == other->prop)) {
865                         Py_RETURN_NONE;
866                 }
867
868                 /* XXX, possible one is inside the other */
869                 IDP_MergeGroup(self->prop, other->prop, true);
870         }
871         else if (PyDict_Check(value)) {
872                 while (PyDict_Next(value, &i, &pkey, &pval)) {
873                         BPy_IDGroup_Map_SetItem(self, pkey, pval);
874                         if (PyErr_Occurred()) return NULL;
875                 }
876         }
877         else {
878                 PyErr_Format(PyExc_TypeError,
879                              "expected a dict or an IDPropertyGroup type, not a %.200s",
880                              Py_TYPE(value)->tp_name);
881                 return NULL;
882         }
883
884
885         Py_RETURN_NONE;
886 }
887
888 static PyObject *BPy_IDGroup_to_dict(BPy_IDProperty *self)
889 {
890         return BPy_IDGroup_MapDataToPy(self->prop);
891 }
892
893 static PyObject *BPy_IDGroup_clear(BPy_IDProperty *self)
894 {
895         IDP_ClearProperty(self->prop);
896         Py_RETURN_NONE;
897 }
898
899 /* Matches python dict.get(key, [default]) */
900 static PyObject *BPy_IDGroup_Get(BPy_IDProperty *self, PyObject *args)
901 {
902         IDProperty *idprop;
903         const char *key;
904         PyObject *def = Py_None;
905
906         if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
907                 return NULL;
908
909         idprop = IDP_GetPropertyFromGroup(self->prop, key);
910         if (idprop) {
911                 PyObject *pyobj = BPy_IDGroup_WrapData(self->id, idprop, self->prop);
912                 if (pyobj)
913                         return pyobj;
914         }
915
916         Py_INCREF(def);
917         return def;
918 }
919
920 static struct PyMethodDef BPy_IDGroup_methods[] = {
921         {"pop", (PyCFunction)BPy_IDGroup_Pop, METH_O,
922          "pop an item from the group; raises KeyError if the item doesn't exist"},
923         {"iteritems", (PyCFunction)BPy_IDGroup_IterItems, METH_NOARGS,
924          "iterate through the items in the dict; behaves like dictionary method iteritems"},
925         {"keys", (PyCFunction)BPy_IDGroup_GetKeys, METH_NOARGS,
926          "get the keys associated with this group as a list of strings"},
927         {"values", (PyCFunction)BPy_IDGroup_GetValues, METH_NOARGS,
928          "get the values associated with this group"},
929         {"items", (PyCFunction)BPy_IDGroup_GetItems, METH_NOARGS,
930          "get the items associated with this group"},
931         {"update", (PyCFunction)BPy_IDGroup_Update, METH_O,
932          "updates the values in the group with the values of another or a dict"},
933         {"get", (PyCFunction)BPy_IDGroup_Get, METH_VARARGS,
934          "idprop.get(k[,d]) -> idprop[k] if k in idprop, else d.  d defaults to None"},
935         {"to_dict", (PyCFunction)BPy_IDGroup_to_dict, METH_NOARGS,
936          "return a purely python version of the group"},
937         {"clear", (PyCFunction)BPy_IDGroup_clear, METH_NOARGS,
938          "clear all members from this group"},
939         {NULL, NULL, 0, NULL}
940 };
941
942 static PySequenceMethods BPy_IDGroup_Seq = {
943         (lenfunc) BPy_IDGroup_Map_Len,      /* lenfunc sq_length */
944         NULL,                               /* binaryfunc sq_concat */
945         NULL,                               /* ssizeargfunc sq_repeat */
946         NULL,                               /* ssizeargfunc sq_item */ /* TODO - setting this will allow PySequence_Check to return True */
947         NULL,                               /* intintargfunc ***was_sq_slice*** */
948         NULL,                               /* intobjargproc sq_ass_item */
949         NULL,                               /* ssizeobjargproc ***was_sq_ass_slice*** */
950         (objobjproc) BPy_IDGroup_Contains,  /* objobjproc sq_contains */
951         NULL,                               /* binaryfunc sq_inplace_concat */
952         NULL,                               /* ssizeargfunc sq_inplace_repeat */
953 };
954
955 static PyMappingMethods BPy_IDGroup_Mapping = {
956         (lenfunc)BPy_IDGroup_Map_Len,           /*inquiry mp_length */
957         (binaryfunc)BPy_IDGroup_Map_GetItem,    /*binaryfunc mp_subscript */
958         (objobjargproc)BPy_IDGroup_Map_SetItem, /*objobjargproc mp_ass_subscript */
959 };
960
961 PyTypeObject BPy_IDGroup_Type = {
962         PyVarObject_HEAD_INIT(NULL, 0)
963         /*  For printing, in format "<module>.<name>" */
964         "IDPropertyGroup",       /* char *tp_name; */
965         sizeof(BPy_IDProperty),     /* int tp_basicsize; */
966         0,                          /* tp_itemsize;  For allocation */
967
968         /* Methods to implement standard operations */
969
970         NULL,                       /* destructor tp_dealloc; */
971         NULL,                       /* printfunc tp_print; */
972         NULL,                       /* getattrfunc tp_getattr; */
973         NULL,                       /* setattrfunc tp_setattr; */
974         NULL,                       /* cmpfunc tp_compare; */
975         (reprfunc)BPy_IDGroup_repr,     /* reprfunc tp_repr; */
976
977         /* Method suites for standard classes */
978
979         NULL,                       /* PyNumberMethods *tp_as_number; */
980         &BPy_IDGroup_Seq,           /* PySequenceMethods *tp_as_sequence; */
981         &BPy_IDGroup_Mapping,       /* PyMappingMethods *tp_as_mapping; */
982
983         /* More standard operations (here for binary compatibility) */
984
985         (hashfunc)BPy_IDGroup_hash, /* hashfunc tp_hash; */
986         NULL,                       /* ternaryfunc tp_call; */
987         NULL,                       /* reprfunc tp_str; */
988         NULL,                       /* getattrofunc tp_getattro; */
989         NULL,                       /* setattrofunc tp_setattro; */
990
991         /* Functions to access object as input/output buffer */
992         NULL,                       /* PyBufferProcs *tp_as_buffer; */
993
994         /*** Flags to define presence of optional/expanded features ***/
995         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
996
997         NULL,                       /*  char *tp_doc;  Documentation string */
998         /*** Assigned meaning in release 2.0 ***/
999         /* call function for all accessible objects */
1000         NULL,                       /* traverseproc tp_traverse; */
1001
1002         /* delete references to contained objects */
1003         NULL,                       /* inquiry tp_clear; */
1004
1005         /***  Assigned meaning in release 2.1 ***/
1006         /*** rich comparisons ***/
1007         NULL,                       /* richcmpfunc tp_richcompare; */
1008
1009         /***  weak reference enabler ***/
1010         0,                          /* long tp_weaklistoffset; */
1011
1012         /*** Added in release 2.2 ***/
1013         /*   Iterators */
1014         (getiterfunc)BPy_IDGroup_iter, /* getiterfunc tp_iter; */
1015         NULL,                       /* iternextfunc tp_iternext; */
1016         /*** Attribute descriptor and subclassing stuff ***/
1017         BPy_IDGroup_methods,        /* struct PyMethodDef *tp_methods; */
1018         NULL,                       /* struct PyMemberDef *tp_members; */
1019         BPy_IDGroup_getseters,       /* struct PyGetSetDef *tp_getset; */
1020 };
1021
1022 /********Array Wrapper********/
1023
1024 static PyTypeObject *idp_array_py_type(BPy_IDArray *self, bool *r_is_double)
1025 {
1026         switch (self->prop->subtype) {
1027                 case IDP_FLOAT:
1028                         *r_is_double = false;
1029                         return &PyFloat_Type;
1030                 case IDP_DOUBLE:
1031                         *r_is_double = true;
1032                         return &PyFloat_Type;
1033                 case IDP_INT:
1034                         *r_is_double = false;
1035                         return &PyLong_Type;
1036                 default:
1037                         *r_is_double = false;
1038                         return NULL;
1039         }
1040 }
1041
1042 static PyObject *BPy_IDArray_repr(BPy_IDArray *self)
1043 {
1044         return PyUnicode_FromFormat("<bpy id property array [%d]>", self->prop->len);
1045 }
1046
1047 static PyObject *BPy_IDArray_GetType(BPy_IDArray *self)
1048 {
1049         switch (self->prop->subtype) {
1050                 case IDP_FLOAT:  return PyUnicode_FromString("f");
1051                 case IDP_DOUBLE: return PyUnicode_FromString("d");
1052                 case IDP_INT:    return PyUnicode_FromString("i");
1053         }
1054
1055         PyErr_Format(PyExc_RuntimeError,
1056                      "%s: invalid/corrupt array type '%d'!",
1057                      __func__, self->prop->subtype);
1058
1059         return NULL;
1060 }
1061
1062 static PyGetSetDef BPy_IDArray_getseters[] = {
1063         /* matches pythons array.typecode */
1064         {(char *)"typecode", (getter)BPy_IDArray_GetType, (setter)NULL, (char *)"The type of the data in the array, is an int.", NULL},
1065         {NULL, NULL, NULL, NULL, NULL},
1066 };
1067
1068 static PyObject *BPy_IDArray_to_list(BPy_IDArray *self)
1069 {
1070         return BPy_IDGroup_MapDataToPy(self->prop);
1071 }
1072
1073 static PyMethodDef BPy_IDArray_methods[] = {
1074         {"to_list", (PyCFunction)BPy_IDArray_to_list, METH_NOARGS,
1075          "return the array as a list"},
1076         {NULL, NULL, 0, NULL}
1077 };
1078
1079 static int BPy_IDArray_Len(BPy_IDArray *self)
1080 {
1081         return self->prop->len;
1082 }
1083
1084 static PyObject *BPy_IDArray_GetItem(BPy_IDArray *self, int index)
1085 {
1086         if (index < 0 || index >= self->prop->len) {
1087                 PyErr_SetString(PyExc_IndexError, "index out of range!");
1088                 return NULL;
1089         }
1090
1091         switch (self->prop->subtype) {
1092                 case IDP_FLOAT:
1093                         return PyFloat_FromDouble(((float *)IDP_Array(self->prop))[index]);
1094                 case IDP_DOUBLE:
1095                         return PyFloat_FromDouble(((double *)IDP_Array(self->prop))[index]);
1096                 case IDP_INT:
1097                         return PyLong_FromLong((long)((int *)IDP_Array(self->prop))[index]);
1098         }
1099
1100         PyErr_Format(PyExc_RuntimeError,
1101                      "%s: invalid/corrupt array type '%d'!",
1102                      __func__, self->prop->subtype);
1103
1104         return NULL;
1105 }
1106
1107 static int BPy_IDArray_SetItem(BPy_IDArray *self, int index, PyObject *value)
1108 {
1109         if (index < 0 || index >= self->prop->len) {
1110                 PyErr_SetString(PyExc_RuntimeError, "index out of range!");
1111                 return -1;
1112         }
1113
1114         switch (self->prop->subtype) {
1115                 case IDP_FLOAT:
1116                 {
1117                         const float f = (float)PyFloat_AsDouble(value);
1118                         if (f == -1 && PyErr_Occurred()) {
1119                                 return -1;
1120                         }
1121                         ((float *)IDP_Array(self->prop))[index] = f;
1122                         break;
1123                 }
1124                 case IDP_DOUBLE:
1125                 {
1126                         const double d = PyFloat_AsDouble(value);
1127                         if (d == -1 && PyErr_Occurred()) {
1128                                 return -1;
1129                         }
1130                         ((double *)IDP_Array(self->prop))[index] = d;
1131                         break;
1132                 }
1133                 case IDP_INT:
1134                 {
1135                         const int i = _PyLong_AsInt(value);
1136                         if (i == -1 && PyErr_Occurred()) {
1137                                 return -1;
1138                         }
1139
1140                         ((int *)IDP_Array(self->prop))[index] = i;
1141                         break;
1142                 }
1143         }
1144         return 0;
1145 }
1146
1147 static PySequenceMethods BPy_IDArray_Seq = {
1148         (lenfunc) BPy_IDArray_Len,          /* inquiry sq_length */
1149         NULL,                               /* binaryfunc sq_concat */
1150         NULL,                               /* intargfunc sq_repeat */
1151         (ssizeargfunc)BPy_IDArray_GetItem,  /* intargfunc sq_item */
1152         NULL,                               /* intintargfunc sq_slice */
1153         (ssizeobjargproc)BPy_IDArray_SetItem, /* intobjargproc sq_ass_item */
1154         NULL,                               /* intintobjargproc sq_ass_slice */
1155         NULL,                               /* objobjproc sq_contains */
1156         /* Added in release 2.0 */
1157         NULL,                               /* binaryfunc sq_inplace_concat */
1158         NULL,                               /* intargfunc sq_inplace_repeat */
1159 };
1160
1161
1162
1163 /* sequence slice (get): idparr[a:b] */
1164 static PyObject *BPy_IDArray_slice(BPy_IDArray *self, int begin, int end)
1165 {
1166         IDProperty *prop = self->prop;
1167         PyObject *tuple;
1168         int count;
1169
1170         CLAMP(begin, 0, prop->len);
1171         if (end < 0) end = prop->len + end + 1;
1172         CLAMP(end, 0, prop->len);
1173         begin = MIN2(begin, end);
1174
1175         tuple = PyTuple_New(end - begin);
1176
1177         switch (prop->subtype) {
1178                 case IDP_FLOAT:
1179                 {
1180                         const float *array = (float *)IDP_Array(prop);
1181                         for (count = begin; count < end; count++) {
1182                                 PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
1183                         }
1184                         break;
1185                 }
1186                 case IDP_DOUBLE:
1187                 {
1188                         const double *array = (double *)IDP_Array(prop);
1189                         for (count = begin; count < end; count++) {
1190                                 PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
1191                         }
1192                         break;
1193                 }
1194                 case IDP_INT:
1195                 {
1196                         const int *array = (int *)IDP_Array(prop);
1197                         for (count = begin; count < end; count++) {
1198                                 PyTuple_SET_ITEM(tuple, count - begin, PyLong_FromLong(array[count]));
1199                         }
1200                         break;
1201                 }
1202         }
1203
1204         return tuple;
1205 }
1206 /* sequence slice (set): idparr[a:b] = value */
1207 static int BPy_IDArray_ass_slice(BPy_IDArray *self, int begin, int end, PyObject *seq)
1208 {
1209         IDProperty *prop = self->prop;
1210         bool is_double;
1211         const PyTypeObject *py_type = idp_array_py_type(self, &is_double);
1212         const size_t elem_size = is_double ? sizeof(double) : sizeof(float);
1213         size_t alloc_len;
1214         size_t size;
1215         void *vec;
1216
1217         CLAMP(begin, 0, prop->len);
1218         CLAMP(end, 0, prop->len);
1219         begin = MIN2(begin, end);
1220
1221         size = (end - begin);
1222         alloc_len = size * elem_size;
1223
1224         vec = MEM_mallocN(alloc_len, "array assignment"); /* NOTE: we count on int/float being the same size here */
1225         if (PyC_AsArray(vec, seq, size, py_type, is_double, "slice assignment: ") == -1) {
1226                 MEM_freeN(vec);
1227                 return -1;
1228         }
1229
1230         memcpy((void *)(((char *)IDP_Array(prop)) + (begin * elem_size)), vec, alloc_len);
1231
1232         MEM_freeN(vec);
1233         return 0;
1234 }
1235
1236 static PyObject *BPy_IDArray_subscript(BPy_IDArray *self, PyObject *item)
1237 {
1238         if (PyIndex_Check(item)) {
1239                 Py_ssize_t i;
1240                 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1241                 if (i == -1 && PyErr_Occurred())
1242                         return NULL;
1243                 if (i < 0)
1244                         i += self->prop->len;
1245                 return BPy_IDArray_GetItem(self, i);
1246         }
1247         else if (PySlice_Check(item)) {
1248                 Py_ssize_t start, stop, step, slicelength;
1249
1250                 if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0)
1251                         return NULL;
1252
1253                 if (slicelength <= 0) {
1254                         return PyTuple_New(0);
1255                 }
1256                 else if (step == 1) {
1257                         return BPy_IDArray_slice(self, start, stop);
1258                 }
1259                 else {
1260                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
1261                         return NULL;
1262                 }
1263         }
1264         else {
1265                 PyErr_Format(PyExc_TypeError,
1266                              "vector indices must be integers, not %.200s",
1267                              __func__, Py_TYPE(item)->tp_name);
1268                 return NULL;
1269         }
1270 }
1271
1272 static int BPy_IDArray_ass_subscript(BPy_IDArray *self, PyObject *item, PyObject *value)
1273 {
1274         if (PyIndex_Check(item)) {
1275                 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1276                 if (i == -1 && PyErr_Occurred())
1277                         return -1;
1278                 if (i < 0)
1279                         i += self->prop->len;
1280                 return BPy_IDArray_SetItem(self, i, value);
1281         }
1282         else if (PySlice_Check(item)) {
1283                 Py_ssize_t start, stop, step, slicelength;
1284
1285                 if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0)
1286                         return -1;
1287
1288                 if (step == 1)
1289                         return BPy_IDArray_ass_slice(self, start, stop, value);
1290                 else {
1291                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
1292                         return -1;
1293                 }
1294         }
1295         else {
1296                 PyErr_Format(PyExc_TypeError,
1297                              "vector indices must be integers, not %.200s",
1298                              Py_TYPE(item)->tp_name);
1299                 return -1;
1300         }
1301 }
1302
1303 static PyMappingMethods BPy_IDArray_AsMapping = {
1304         (lenfunc)BPy_IDArray_Len,
1305         (binaryfunc)BPy_IDArray_subscript,
1306         (objobjargproc)BPy_IDArray_ass_subscript
1307 };
1308
1309
1310 PyTypeObject BPy_IDArray_Type = {
1311         PyVarObject_HEAD_INIT(NULL, 0)
1312         /*  For printing, in format "<module>.<name>" */
1313         "IDPropertyArray",           /* char *tp_name; */
1314         sizeof(BPy_IDArray),       /* int tp_basicsize; */
1315         0,                          /* tp_itemsize;  For allocation */
1316
1317         /* Methods to implement standard operations */
1318
1319         NULL,                       /* destructor tp_dealloc; */
1320         NULL,                       /* printfunc tp_print; */
1321         NULL,     /* getattrfunc tp_getattr; */
1322         NULL,     /* setattrfunc tp_setattr; */
1323         NULL,                       /* cmpfunc tp_compare; */
1324         (reprfunc)BPy_IDArray_repr,     /* reprfunc tp_repr; */
1325
1326         /* Method suites for standard classes */
1327
1328         NULL,                       /* PyNumberMethods *tp_as_number; */
1329         &BPy_IDArray_Seq,           /* PySequenceMethods *tp_as_sequence; */
1330         &BPy_IDArray_AsMapping,     /* PyMappingMethods *tp_as_mapping; */
1331
1332         /* More standard operations (here for binary compatibility) */
1333
1334         NULL,                       /* hashfunc tp_hash; */
1335         NULL,                       /* ternaryfunc tp_call; */
1336         NULL,                       /* reprfunc tp_str; */
1337         NULL,                       /* getattrofunc tp_getattro; */
1338         NULL,                       /* setattrofunc tp_setattro; */
1339
1340         /* Functions to access object as input/output buffer */
1341         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1342
1343         /*** Flags to define presence of optional/expanded features ***/
1344         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
1345
1346         NULL,                       /*  char *tp_doc;  Documentation string */
1347         /*** Assigned meaning in release 2.0 ***/
1348         /* call function for all accessible objects */
1349         NULL,                       /* traverseproc tp_traverse; */
1350
1351         /* delete references to contained objects */
1352         NULL,                       /* inquiry tp_clear; */
1353
1354         /***  Assigned meaning in release 2.1 ***/
1355         /*** rich comparisons ***/
1356         NULL,                       /* richcmpfunc tp_richcompare; */
1357
1358         /***  weak reference enabler ***/
1359         0,                          /* long tp_weaklistoffset; */
1360
1361         /*** Added in release 2.2 ***/
1362         /*   Iterators */
1363         NULL,                       /* getiterfunc tp_iter; */
1364         NULL,                       /* iternextfunc tp_iternext; */
1365
1366         /*** Attribute descriptor and subclassing stuff ***/
1367         BPy_IDArray_methods,        /* struct PyMethodDef *tp_methods; */
1368         NULL,                       /* struct PyMemberDef *tp_members; */
1369         BPy_IDArray_getseters,       /* struct PyGetSetDef *tp_getset; */
1370         NULL,                       /* struct _typeobject *tp_base; */
1371         NULL,                       /* PyObject *tp_dict; */
1372         NULL,                       /* descrgetfunc tp_descr_get; */
1373         NULL,                       /* descrsetfunc tp_descr_set; */
1374         0,                          /* long tp_dictoffset; */
1375         NULL,                       /* initproc tp_init; */
1376         NULL,                       /* allocfunc tp_alloc; */
1377         NULL,                       /* newfunc tp_new; */
1378         /*  Low-level free-memory routine */
1379         NULL,                       /* freefunc tp_free;  */
1380         /* For PyObject_IS_GC */
1381         NULL,                       /* inquiry tp_is_gc;  */
1382         NULL,                       /* PyObject *tp_bases; */
1383         /* method resolution order */
1384         NULL,                       /* PyObject *tp_mro;  */
1385         NULL,                       /* PyObject *tp_cache; */
1386         NULL,                       /* PyObject *tp_subclasses; */
1387         NULL,                       /* PyObject *tp_weaklist; */
1388         NULL
1389 };
1390
1391 /*********** ID Property Group iterator ********/
1392
1393 static PyObject *IDGroup_Iter_repr(BPy_IDGroup_Iter *self)
1394 {
1395         return PyUnicode_FromFormat("(ID Property Group Iter \"%s\")", self->group->prop->name);
1396 }
1397
1398 static PyObject *BPy_Group_Iter_Next(BPy_IDGroup_Iter *self)
1399 {
1400
1401         if (self->cur) {
1402                 PyObject *ret;
1403                 IDProperty *cur;
1404
1405                 cur = self->cur;
1406                 self->cur = self->cur->next;
1407
1408                 if (self->mode == IDPROP_ITER_ITEMS) {
1409                         ret = PyTuple_New(2);
1410                         PyTuple_SET_ITEMS(ret,
1411                                 PyUnicode_FromString(cur->name),
1412                                 BPy_IDGroup_WrapData(self->group->id, cur, self->group->prop));
1413                         return ret;
1414                 }
1415                 else {
1416                         return PyUnicode_FromString(cur->name);
1417                 }
1418         }
1419         else {
1420                 PyErr_SetNone(PyExc_StopIteration);
1421                 return NULL;
1422         }
1423 }
1424
1425 PyTypeObject BPy_IDGroup_Iter_Type = {
1426         PyVarObject_HEAD_INIT(NULL, 0)
1427         /*  For printing, in format "<module>.<name>" */
1428         "IDPropertyGroupIter",           /* char *tp_name; */
1429         sizeof(BPy_IDGroup_Iter),       /* int tp_basicsize; */
1430         0,                          /* tp_itemsize;  For allocation */
1431
1432         /* Methods to implement standard operations */
1433
1434         NULL,                       /* destructor tp_dealloc; */
1435         NULL,                       /* printfunc tp_print; */
1436         NULL,     /* getattrfunc tp_getattr; */
1437         NULL,     /* setattrfunc tp_setattr; */
1438         NULL,                       /* cmpfunc tp_compare; */
1439         (reprfunc) IDGroup_Iter_repr,     /* reprfunc tp_repr; */
1440
1441         /* Method suites for standard classes */
1442
1443         NULL,                       /* PyNumberMethods *tp_as_number; */
1444         NULL,                       /* PySequenceMethods *tp_as_sequence; */
1445         NULL,                       /* PyMappingMethods *tp_as_mapping; */
1446
1447         /* More standard operations (here for binary compatibility) */
1448
1449         NULL,                       /* hashfunc tp_hash; */
1450         NULL,                       /* ternaryfunc tp_call; */
1451         NULL,                       /* reprfunc tp_str; */
1452         NULL,                       /* getattrofunc tp_getattro; */
1453         NULL,                       /* setattrofunc tp_setattro; */
1454
1455         /* Functions to access object as input/output buffer */
1456         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1457
1458         /*** Flags to define presence of optional/expanded features ***/
1459         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
1460
1461         NULL,                       /*  char *tp_doc;  Documentation string */
1462         /*** Assigned meaning in release 2.0 ***/
1463         /* call function for all accessible objects */
1464         NULL,                       /* traverseproc tp_traverse; */
1465
1466         /* delete references to contained objects */
1467         NULL,                       /* inquiry tp_clear; */
1468
1469         /***  Assigned meaning in release 2.1 ***/
1470         /*** rich comparisons ***/
1471         NULL,                       /* richcmpfunc tp_richcompare; */
1472
1473         /***  weak reference enabler ***/
1474         0,                          /* long tp_weaklistoffset; */
1475
1476         /*** Added in release 2.2 ***/
1477         /*   Iterators */
1478         PyObject_SelfIter,                  /* getiterfunc tp_iter; */
1479         (iternextfunc) BPy_Group_Iter_Next, /* iternextfunc tp_iternext; */
1480 };
1481
1482 void IDProp_Init_Types(void)
1483 {
1484         PyType_Ready(&BPy_IDGroup_Type);
1485         PyType_Ready(&BPy_IDGroup_Iter_Type);
1486         PyType_Ready(&BPy_IDArray_Type);
1487 }
1488
1489 /*----------------------------MODULE INIT-------------------------*/
1490
1491 /* --- */
1492
1493 static struct PyModuleDef IDProp_types_module_def = {
1494         PyModuleDef_HEAD_INIT,
1495         "idprop.types",  /* m_name */
1496         NULL,  /* m_doc */
1497         0,  /* m_size */
1498         NULL,  /* m_methods */
1499         NULL,  /* m_reload */
1500         NULL,  /* m_traverse */
1501         NULL,  /* m_clear */
1502         NULL,  /* m_free */
1503 };
1504
1505 static PyObject *BPyInit_idprop_types(void)
1506 {
1507         PyObject *submodule;
1508
1509         submodule = PyModule_Create(&IDProp_types_module_def);
1510
1511         IDProp_Init_Types();
1512
1513 #define MODULE_TYPE_ADD(s, t) \
1514         PyModule_AddObject(s, t.tp_name, (PyObject *)&t); Py_INCREF((PyObject *)&t)
1515
1516         /* bmesh_py_types.c */
1517         MODULE_TYPE_ADD(submodule, BPy_IDGroup_Type);
1518         MODULE_TYPE_ADD(submodule, BPy_IDGroup_Iter_Type);
1519         MODULE_TYPE_ADD(submodule, BPy_IDArray_Type);
1520
1521 #undef MODULE_TYPE_ADD
1522
1523         return submodule;
1524 }
1525
1526 /* --- */
1527
1528 static PyMethodDef IDProp_methods[] = {
1529         {NULL, NULL, 0, NULL}
1530 };
1531
1532
1533 PyDoc_STRVAR(IDProp_module_doc,
1534 "This module provides access id property types (currently mainly for docs)."
1535 );
1536 static struct PyModuleDef IDProp_module_def = {
1537         PyModuleDef_HEAD_INIT,
1538         "idprop",  /* m_name */
1539         IDProp_module_doc,  /* m_doc */
1540         0,  /* m_size */
1541         IDProp_methods,  /* m_methods */
1542         NULL,  /* m_reload */
1543         NULL,  /* m_traverse */
1544         NULL,  /* m_clear */
1545         NULL,  /* m_free */
1546 };
1547
1548 PyObject *BPyInit_idprop(void)
1549 {
1550         PyObject *mod;
1551         PyObject *submodule;
1552         PyObject *sys_modules = PyThreadState_GET()->interp->modules;
1553
1554         mod = PyModule_Create(&IDProp_module_def);
1555
1556         /* idprop.types */
1557         PyModule_AddObject(mod, "types", (submodule = BPyInit_idprop_types()));
1558         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
1559         Py_INCREF(submodule);
1560
1561         return mod;
1562 }
1563
1564
1565 #ifndef NDEBUG
1566 /* -------------------------------------------------------------------- */
1567 /* debug only function */
1568
1569 void IDP_spit(IDProperty *prop)
1570 {
1571         if (prop) {
1572                 PyGILState_STATE gilstate;
1573                 bool use_gil = true; /* !PyC_IsInterpreterActive(); */
1574                 PyObject *ret_dict;
1575                 PyObject *ret_str;
1576
1577                 if (use_gil) {
1578                         gilstate = PyGILState_Ensure();
1579                 }
1580
1581                 /* to_dict() */
1582                 ret_dict = BPy_IDGroup_MapDataToPy(prop);
1583                 ret_str = PyObject_Repr(ret_dict);
1584                 Py_DECREF(ret_dict);
1585
1586                 printf("IDProperty(%p): %s\n", prop, _PyUnicode_AsString(ret_str));
1587
1588                 Py_DECREF(ret_str);
1589
1590                 if (use_gil) {
1591                         PyGILState_Release(gilstate);
1592                 }
1593         }
1594         else {
1595                 printf("IDProperty: <NIL>\n");
1596         }
1597 }
1598
1599 #endif