add typechecks when assigning id-property arrays from python (overflows and errors...
[blender.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_string.h"
33 #include "BLI_utildefines.h"
34
35 #include "idprop_py_api.h"
36
37
38 #include "BKE_idprop.h"
39
40
41 #define USE_STRING_COERCE
42
43 #ifdef USE_STRING_COERCE
44 #include "py_capi_utils.h"
45 #endif
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 int idp_sequence_type(PyObject *seq_fast)
301 {
302         PyObject *item;
303         int 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 = (char *)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)) == -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                 IDP_ReplaceInGroup(group, prop);
515         }
516
517         return true;
518 }
519
520 int BPy_Wrap_SetMapItem(IDProperty *prop, PyObject *key, PyObject *val)
521 {
522         if (prop->type != IDP_GROUP) {
523                 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
524                 return -1;
525         }
526
527         if (val == NULL) { /* del idprop[key] */
528                 IDProperty *pkey = IDP_GetPropertyFromGroup(prop, _PyUnicode_AsString(key));
529                 if (pkey) {
530                         IDP_FreeFromGroup(prop, pkey);
531                         return 0;
532                 }
533                 else {
534                         PyErr_SetString(PyExc_KeyError, "property not found in group");
535                         return -1;
536                 }
537         }
538         else {
539                 bool ok;
540
541                 ok = BPy_IDProperty_Map_ValidateAndCreate(key, prop, val);
542                 if (ok == false) {
543                         return -1;
544                 }
545
546                 return 0;
547         }
548 }
549
550 static int BPy_IDGroup_Map_SetItem(BPy_IDProperty *self, PyObject *key, PyObject *val)
551 {
552         return BPy_Wrap_SetMapItem(self->prop, key, val);
553 }
554
555 static PyObject *BPy_IDGroup_iter(BPy_IDProperty *self)
556 {
557         BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
558         iter->group = self;
559         iter->mode = IDPROP_ITER_KEYS;
560         iter->cur = self->prop->data.group.first;
561         Py_XINCREF(iter);
562         return (PyObject *)iter;
563 }
564
565 /* for simple, non nested types this is the same as BPy_IDGroup_WrapData */
566 static PyObject *BPy_IDGroup_MapDataToPy(IDProperty *prop)
567 {
568         switch (prop->type) {
569                 case IDP_STRING:
570                         return idprop_py_from_idp_string(prop);
571                 case IDP_INT:
572                         return idprop_py_from_idp_int(prop);
573                 case IDP_FLOAT:
574                         return idprop_py_from_idp_float(prop);
575                 case IDP_DOUBLE:
576                         return idprop_py_from_idp_double(prop);
577                 case IDP_ARRAY:
578                 {
579                         PyObject *seq = PyList_New(prop->len);
580                         int i;
581
582                         if (!seq) {
583                                 PyErr_Format(PyExc_RuntimeError,
584                                              "%s: IDP_ARRAY: PyList_New(%d) failed",
585                                              __func__, prop->len);
586                                 return NULL;
587                         }
588
589                         switch (prop->subtype) {
590                                 case IDP_FLOAT:
591                                 {
592                                         float *array = (float *)IDP_Array(prop);
593                                         for (i = 0; i < prop->len; i++) {
594                                                 PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
595                                         }
596                                         break;
597                                 }
598                                 case IDP_DOUBLE:
599                                 {
600                                         double *array = (double *)IDP_Array(prop);
601                                         for (i = 0; i < prop->len; i++) {
602                                                 PyList_SET_ITEM(seq, i, PyFloat_FromDouble(array[i]));
603                                         }
604                                         break;
605                                 }
606                                 case IDP_INT:
607                                 {
608                                         int *array = (int *)IDP_Array(prop);
609                                         for (i = 0; i < prop->len; i++) {
610                                                 PyList_SET_ITEM(seq, i, PyLong_FromLong(array[i]));
611                                         }
612                                         break;
613                                 }
614                                 default:
615                                         PyErr_Format(PyExc_RuntimeError,
616                                                      "%s: invalid/corrupt array type '%d'!",
617                                                      __func__, prop->subtype);
618                                         Py_DECREF(seq);
619                                         return NULL;
620                         }
621
622                         return seq;
623                 }
624                 case IDP_IDPARRAY:
625                 {
626                         PyObject *seq = PyList_New(prop->len), *wrap;
627                         IDProperty *array = IDP_IDPArray(prop);
628                         int i;
629
630                         if (!seq) {
631                                 PyErr_Format(PyExc_RuntimeError,
632                                              "%s: IDP_IDPARRAY: PyList_New(%d) failed",
633                                              __func__, prop->len);
634                                 return NULL;
635                         }
636
637                         for (i = 0; i < prop->len; i++) {
638                                 wrap = BPy_IDGroup_MapDataToPy(array++);
639
640                                 if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
641                                         return NULL;
642
643                                 PyList_SET_ITEM(seq, i, wrap);
644                         }
645                         return seq;
646                 }
647                 case IDP_GROUP:
648                 {
649                         PyObject *dict = PyDict_New(), *wrap;
650                         IDProperty *loop;
651
652                         for (loop = prop->data.group.first; loop; loop = loop->next) {
653                                 wrap = BPy_IDGroup_MapDataToPy(loop);
654
655                                 if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
656                                         return NULL;
657
658                                 PyDict_SetItemString(dict, loop->name, wrap);
659                                 Py_DECREF(wrap);
660                         }
661                         return dict;
662                 }
663         }
664
665         PyErr_Format(PyExc_RuntimeError,
666                      "%s ERROR: '%s' property exists with a bad type code '%d'!",
667                      __func__, prop->name, prop->type);
668         return NULL;
669 }
670
671 static PyObject *BPy_IDGroup_Pop(BPy_IDProperty *self, PyObject *value)
672 {
673         IDProperty *idprop;
674         PyObject *pyform;
675         const char *name = _PyUnicode_AsString(value);
676
677         if (!name) {
678                 PyErr_Format(PyExc_TypeError,
679                              "pop expected at least a string argument, not %.200s",
680                              Py_TYPE(value)->tp_name);
681                 return NULL;
682         }
683
684         idprop = IDP_GetPropertyFromGroup(self->prop, name);
685
686         if (idprop) {
687                 pyform = BPy_IDGroup_MapDataToPy(idprop);
688
689                 if (!pyform) {
690                         /* ok something bad happened with the pyobject,
691                          * so don't remove the prop from the group.  if pyform is
692                          * NULL, then it already should have raised an exception.*/
693                         return NULL;
694                 }
695
696                 IDP_RemoveFromGroup(self->prop, idprop);
697                 return pyform;
698         }
699
700         PyErr_SetString(PyExc_KeyError, "item not in group");
701         return NULL;
702 }
703
704 static PyObject *BPy_IDGroup_IterItems(BPy_IDProperty *self)
705 {
706         BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &BPy_IDGroup_Iter_Type);
707         iter->group = self;
708         iter->mode = IDPROP_ITER_ITEMS;
709         iter->cur = self->prop->data.group.first;
710         Py_XINCREF(iter);
711         return (PyObject *)iter;
712 }
713
714 /* utility function */
715 static void BPy_IDGroup_CorrectListLen(IDProperty *prop, PyObject *seq, int len, const char *func)
716 {
717         int j;
718
719         printf("%s: ID Property Error found and corrected!\n", func);
720
721         /*fill rest of list with valid references to None*/
722         for (j = len; j < prop->len; j++) {
723                 Py_INCREF(Py_None);
724                 PyList_SET_ITEM(seq, j, Py_None);
725         }
726
727         /*set correct group length*/
728         prop->len = len;
729 }
730
731 PyObject *BPy_Wrap_GetKeys(IDProperty *prop)
732 {
733         PyObject *list = PyList_New(prop->len);
734         IDProperty *loop;
735         int i;
736
737         for (i = 0, loop = prop->data.group.first; loop && (i < prop->len); loop = loop->next, i++)
738                 PyList_SET_ITEM(list, i, PyUnicode_FromString(loop->name));
739
740         /* if the id prop is corrupt, count the remaining */
741         for ( ; loop; loop = loop->next, i++) {
742                 /* pass */
743         }
744
745         if (i != prop->len) { /* if the loop didnt finish, we know the length is wrong */
746                 BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
747                 Py_DECREF(list); /*free the list*/
748                 /*call self again*/
749                 return BPy_Wrap_GetKeys(prop);
750         }
751
752         return list;
753 }
754
755 PyObject *BPy_Wrap_GetValues(ID *id, IDProperty *prop)
756 {
757         PyObject *list = PyList_New(prop->len);
758         IDProperty *loop;
759         int i;
760
761         for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
762                 PyList_SET_ITEM(list, i, BPy_IDGroup_WrapData(id, loop, prop));
763         }
764
765         if (i != prop->len) {
766                 BPy_IDGroup_CorrectListLen(prop, list, i, __func__);
767                 Py_DECREF(list); /*free the list*/
768                 /*call self again*/
769                 return BPy_Wrap_GetValues(id, prop);
770         }
771
772         return list;
773 }
774
775 PyObject *BPy_Wrap_GetItems(ID *id, IDProperty *prop)
776 {
777         PyObject *seq = PyList_New(prop->len);
778         IDProperty *loop;
779         int i;
780
781         for (i = 0, loop = prop->data.group.first; loop; loop = loop->next, i++) {
782                 PyObject *item = PyTuple_New(2);
783                 PyTuple_SET_ITEM(item, 0, PyUnicode_FromString(loop->name));
784                 PyTuple_SET_ITEM(item, 1, BPy_IDGroup_WrapData(id, loop, prop));
785                 PyList_SET_ITEM(seq, i, item);
786         }
787
788         if (i != prop->len) {
789                 BPy_IDGroup_CorrectListLen(prop, seq, i, __func__);
790                 Py_DECREF(seq); /*free the list*/
791                 /*call self again*/
792                 return BPy_Wrap_GetItems(id, prop);
793         }
794
795         return seq;
796 }
797
798
799 static PyObject *BPy_IDGroup_GetKeys(BPy_IDProperty *self)
800 {
801         return BPy_Wrap_GetKeys(self->prop);
802 }
803
804 static PyObject *BPy_IDGroup_GetValues(BPy_IDProperty *self)
805 {
806         return BPy_Wrap_GetValues(self->id, self->prop);
807 }
808
809 static PyObject *BPy_IDGroup_GetItems(BPy_IDProperty *self)
810 {
811         return BPy_Wrap_GetItems(self->id, self->prop);
812 }
813
814 static int BPy_IDGroup_Contains(BPy_IDProperty *self, PyObject *value)
815 {
816         const char *name = _PyUnicode_AsString(value);
817
818         if (!name) {
819                 PyErr_Format(PyExc_TypeError,
820                              "expected a string, not a %.200s",
821                              Py_TYPE(value)->tp_name);
822                 return -1;
823         }
824
825         return IDP_GetPropertyFromGroup(self->prop, name) ? 1 : 0;
826 }
827
828 static PyObject *BPy_IDGroup_Update(BPy_IDProperty *self, PyObject *value)
829 {
830         PyObject *pkey, *pval;
831         Py_ssize_t i = 0;
832
833         if (BPy_IDGroup_Check(value)) {
834                 BPy_IDProperty *other = (BPy_IDProperty *)value;
835                 if (UNLIKELY(self->prop == other->prop)) {
836                         Py_RETURN_NONE;
837                 }
838
839                 /* XXX, possible one is inside the other */
840                 IDP_MergeGroup(self->prop, other->prop, TRUE);
841         }
842         else if (PyDict_Check(value)) {
843                 while (PyDict_Next(value, &i, &pkey, &pval)) {
844                         BPy_IDGroup_Map_SetItem(self, pkey, pval);
845                         if (PyErr_Occurred()) return NULL;
846                 }
847         }
848         else {
849                 PyErr_Format(PyExc_TypeError,
850                              "expected a dict or an IDPropertyGroup type, not a %.200s",
851                              Py_TYPE(value)->tp_name);
852                 return NULL;
853         }
854
855
856         Py_RETURN_NONE;
857 }
858
859 static PyObject *BPy_IDGroup_to_dict(BPy_IDProperty *self)
860 {
861         return BPy_IDGroup_MapDataToPy(self->prop);
862 }
863
864 static PyObject *BPy_IDGroup_clear(BPy_IDProperty *self)
865 {
866         IDP_ClearProperty(self->prop);
867         Py_RETURN_NONE;
868 }
869
870 /* Matches python dict.get(key, [default]) */
871 static PyObject *BPy_IDGroup_Get(BPy_IDProperty *self, PyObject *args)
872 {
873         IDProperty *idprop;
874         char *key;
875         PyObject *def = Py_None;
876
877         if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
878                 return NULL;
879
880         idprop = IDP_GetPropertyFromGroup(self->prop, key);
881         if (idprop) {
882                 PyObject *pyobj = BPy_IDGroup_WrapData(self->id, idprop, self->prop);
883                 if (pyobj)
884                         return pyobj;
885         }
886
887         Py_INCREF(def);
888         return def;
889 }
890
891 static struct PyMethodDef BPy_IDGroup_methods[] = {
892         {"pop", (PyCFunction)BPy_IDGroup_Pop, METH_O,
893          "pop an item from the group; raises KeyError if the item doesn't exist"},
894         {"iteritems", (PyCFunction)BPy_IDGroup_IterItems, METH_NOARGS,
895          "iterate through the items in the dict; behaves like dictionary method iteritems"},
896         {"keys", (PyCFunction)BPy_IDGroup_GetKeys, METH_NOARGS,
897          "get the keys associated with this group as a list of strings"},
898         {"values", (PyCFunction)BPy_IDGroup_GetValues, METH_NOARGS,
899          "get the values associated with this group"},
900         {"items", (PyCFunction)BPy_IDGroup_GetItems, METH_NOARGS,
901          "get the items associated with this group"},
902         {"update", (PyCFunction)BPy_IDGroup_Update, METH_O,
903          "updates the values in the group with the values of another or a dict"},
904         {"get", (PyCFunction)BPy_IDGroup_Get, METH_VARARGS,
905          "idprop.get(k[,d]) -> idprop[k] if k in idprop, else d.  d defaults to None"},
906         {"to_dict", (PyCFunction)BPy_IDGroup_to_dict, METH_NOARGS,
907          "return a purely python version of the group"},
908         {"clear", (PyCFunction)BPy_IDGroup_clear, METH_NOARGS,
909          "clear all members from this group"},
910         {NULL, NULL, 0, NULL}
911 };
912
913 static PySequenceMethods BPy_IDGroup_Seq = {
914         (lenfunc) BPy_IDGroup_Map_Len,      /* lenfunc sq_length */
915         NULL,                               /* binaryfunc sq_concat */
916         NULL,                               /* ssizeargfunc sq_repeat */
917         NULL,                               /* ssizeargfunc sq_item */ /* TODO - setting this will allow PySequence_Check to return True */
918         NULL,                               /* intintargfunc ***was_sq_slice*** */
919         NULL,                               /* intobjargproc sq_ass_item */
920         NULL,                               /* ssizeobjargproc ***was_sq_ass_slice*** */
921         (objobjproc) BPy_IDGroup_Contains,  /* objobjproc sq_contains */
922         NULL,                               /* binaryfunc sq_inplace_concat */
923         NULL,                               /* ssizeargfunc sq_inplace_repeat */
924 };
925
926 static PyMappingMethods BPy_IDGroup_Mapping = {
927         (lenfunc)BPy_IDGroup_Map_Len,           /*inquiry mp_length */
928         (binaryfunc)BPy_IDGroup_Map_GetItem,    /*binaryfunc mp_subscript */
929         (objobjargproc)BPy_IDGroup_Map_SetItem, /*objobjargproc mp_ass_subscript */
930 };
931
932 PyTypeObject BPy_IDGroup_Type = {
933         PyVarObject_HEAD_INIT(NULL, 0)
934         /*  For printing, in format "<module>.<name>" */
935         "IDPropertyGroup",       /* char *tp_name; */
936         sizeof(BPy_IDProperty),     /* int tp_basicsize; */
937         0,                          /* tp_itemsize;  For allocation */
938
939         /* Methods to implement standard operations */
940
941         NULL,                       /* destructor tp_dealloc; */
942         NULL,                       /* printfunc tp_print; */
943         NULL,                       /* getattrfunc tp_getattr; */
944         NULL,                       /* setattrfunc tp_setattr; */
945         NULL,                       /* cmpfunc tp_compare; */
946         (reprfunc)BPy_IDGroup_repr,     /* reprfunc tp_repr; */
947
948         /* Method suites for standard classes */
949
950         NULL,                       /* PyNumberMethods *tp_as_number; */
951         &BPy_IDGroup_Seq,           /* PySequenceMethods *tp_as_sequence; */
952         &BPy_IDGroup_Mapping,       /* PyMappingMethods *tp_as_mapping; */
953
954         /* More standard operations (here for binary compatibility) */
955
956         (hashfunc)BPy_IDGroup_hash, /* hashfunc tp_hash; */
957         NULL,                       /* ternaryfunc tp_call; */
958         NULL,                       /* reprfunc tp_str; */
959         NULL,                       /* getattrofunc tp_getattro; */
960         NULL,                       /* setattrofunc tp_setattro; */
961
962         /* Functions to access object as input/output buffer */
963         NULL,                       /* PyBufferProcs *tp_as_buffer; */
964
965         /*** Flags to define presence of optional/expanded features ***/
966         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
967
968         NULL,                       /*  char *tp_doc;  Documentation string */
969         /*** Assigned meaning in release 2.0 ***/
970         /* call function for all accessible objects */
971         NULL,                       /* traverseproc tp_traverse; */
972
973         /* delete references to contained objects */
974         NULL,                       /* inquiry tp_clear; */
975
976         /***  Assigned meaning in release 2.1 ***/
977         /*** rich comparisons ***/
978         NULL,                       /* richcmpfunc tp_richcompare; */
979
980         /***  weak reference enabler ***/
981         0,                          /* long tp_weaklistoffset; */
982
983         /*** Added in release 2.2 ***/
984         /*   Iterators */
985         (getiterfunc)BPy_IDGroup_iter, /* getiterfunc tp_iter; */
986         NULL,                       /* iternextfunc tp_iternext; */
987         /*** Attribute descriptor and subclassing stuff ***/
988         BPy_IDGroup_methods,        /* struct PyMethodDef *tp_methods; */
989         NULL,                       /* struct PyMemberDef *tp_members; */
990         BPy_IDGroup_getseters,       /* struct PyGetSetDef *tp_getset; */
991 };
992
993 /********Array Wrapper********/
994
995 static PyTypeObject *idp_array_py_type(BPy_IDArray *self, short *is_double)
996 {
997         switch (self->prop->subtype) {
998                 case IDP_FLOAT:
999                         *is_double = 0;
1000                         return &PyFloat_Type;
1001                 case IDP_DOUBLE:
1002                         *is_double = 1;
1003                         return &PyFloat_Type;
1004                 case IDP_INT:
1005                         *is_double = 0;
1006                         return &PyLong_Type;
1007         }
1008
1009         *is_double = 0;
1010         return NULL;
1011 }
1012
1013 static PyObject *BPy_IDArray_repr(BPy_IDArray *self)
1014 {
1015         return PyUnicode_FromFormat("<bpy id property array [%d]>", self->prop->len);
1016 }
1017
1018 static PyObject *BPy_IDArray_GetType(BPy_IDArray *self)
1019 {
1020         switch (self->prop->subtype) {
1021                 case IDP_FLOAT:  return PyUnicode_FromString("f");
1022                 case IDP_DOUBLE: return PyUnicode_FromString("d");
1023                 case IDP_INT:    return PyUnicode_FromString("i");
1024         }
1025
1026         PyErr_Format(PyExc_RuntimeError,
1027                      "%s: invalid/corrupt array type '%d'!",
1028                      __func__, self->prop->subtype);
1029
1030         return NULL;
1031 }
1032
1033 static PyGetSetDef BPy_IDArray_getseters[] = {
1034         /* matches pythons array.typecode */
1035         {(char *)"typecode", (getter)BPy_IDArray_GetType, (setter)NULL, (char *)"The type of the data in the array, is an int.", NULL},
1036         {NULL, NULL, NULL, NULL, NULL},
1037 };
1038
1039 static PyObject *BPy_IDArray_to_list(BPy_IDArray *self)
1040 {
1041         return BPy_IDGroup_MapDataToPy(self->prop);
1042 }
1043
1044 static PyMethodDef BPy_IDArray_methods[] = {
1045         {"to_list", (PyCFunction)BPy_IDArray_to_list, METH_NOARGS,
1046          "return the array as a list"},
1047         {NULL, NULL, 0, NULL}
1048 };
1049
1050 static int BPy_IDArray_Len(BPy_IDArray *self)
1051 {
1052         return self->prop->len;
1053 }
1054
1055 static PyObject *BPy_IDArray_GetItem(BPy_IDArray *self, int index)
1056 {
1057         if (index < 0 || index >= self->prop->len) {
1058                 PyErr_SetString(PyExc_IndexError, "index out of range!");
1059                 return NULL;
1060         }
1061
1062         switch (self->prop->subtype) {
1063                 case IDP_FLOAT:
1064                         return PyFloat_FromDouble(((float *)IDP_Array(self->prop))[index]);
1065                 case IDP_DOUBLE:
1066                         return PyFloat_FromDouble(((double *)IDP_Array(self->prop))[index]);
1067                 case IDP_INT:
1068                         return PyLong_FromLong((long)((int *)IDP_Array(self->prop))[index]);
1069         }
1070
1071         PyErr_Format(PyExc_RuntimeError,
1072                      "%s: invalid/corrupt array type '%d'!",
1073                      __func__, self->prop->subtype);
1074
1075         return NULL;
1076 }
1077
1078 static int BPy_IDArray_SetItem(BPy_IDArray *self, int index, PyObject *value)
1079 {
1080         if (index < 0 || index >= self->prop->len) {
1081                 PyErr_SetString(PyExc_RuntimeError, "index out of range!");
1082                 return -1;
1083         }
1084
1085         switch (self->prop->subtype) {
1086                 case IDP_FLOAT:
1087                 {
1088                         const float f = (float)PyFloat_AsDouble(value);
1089                         if (f == -1 && PyErr_Occurred()) {
1090                                 return -1;
1091                         }
1092                         ((float *)IDP_Array(self->prop))[index] = f;
1093                         break;
1094                 }
1095                 case IDP_DOUBLE:
1096                 {
1097                         const double d = PyFloat_AsDouble(value);
1098                         if (d == -1 && PyErr_Occurred()) {
1099                                 return -1;
1100                         }
1101                         ((double *)IDP_Array(self->prop))[index] = d;
1102                         break;
1103                 }
1104                 case IDP_INT:
1105                 {
1106                         const int i = _PyLong_AsInt(value);
1107                         if (i == -1 && PyErr_Occurred()) {
1108                                 return -1;
1109                         }
1110
1111                         ((int *)IDP_Array(self->prop))[index] = i;
1112                         break;
1113                 }
1114         }
1115         return 0;
1116 }
1117
1118 static PySequenceMethods BPy_IDArray_Seq = {
1119         (lenfunc) BPy_IDArray_Len,          /* inquiry sq_length */
1120         NULL,                               /* binaryfunc sq_concat */
1121         NULL,                               /* intargfunc sq_repeat */
1122         (ssizeargfunc)BPy_IDArray_GetItem,  /* intargfunc sq_item */
1123         NULL,                               /* intintargfunc sq_slice */
1124         (ssizeobjargproc)BPy_IDArray_SetItem, /* intobjargproc sq_ass_item */
1125         NULL,                               /* intintobjargproc sq_ass_slice */
1126         NULL,                               /* objobjproc sq_contains */
1127         /* Added in release 2.0 */
1128         NULL,                               /* binaryfunc sq_inplace_concat */
1129         NULL,                               /* intargfunc sq_inplace_repeat */
1130 };
1131
1132
1133
1134 /* sequence slice (get): idparr[a:b] */
1135 static PyObject *BPy_IDArray_slice(BPy_IDArray *self, int begin, int end)
1136 {
1137         IDProperty *prop = self->prop;
1138         PyObject *tuple;
1139         int count;
1140
1141         CLAMP(begin, 0, prop->len);
1142         if (end < 0) end = prop->len + end + 1;
1143         CLAMP(end, 0, prop->len);
1144         begin = MIN2(begin, end);
1145
1146         tuple = PyTuple_New(end - begin);
1147
1148         switch (prop->subtype) {
1149                 case IDP_FLOAT:
1150                 {
1151                         float *array = (float *)IDP_Array(prop);
1152                         for (count = begin; count < end; count++) {
1153                                 PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
1154                         }
1155                         break;
1156                 }
1157                 case IDP_DOUBLE:
1158                 {
1159                         double *array = (double *)IDP_Array(prop);
1160                         for (count = begin; count < end; count++) {
1161                                 PyTuple_SET_ITEM(tuple, count - begin, PyFloat_FromDouble(array[count]));
1162                         }
1163                         break;
1164                 }
1165                 case IDP_INT:
1166                 {
1167                         int *array = (int *)IDP_Array(prop);
1168                         for (count = begin; count < end; count++) {
1169                                 PyTuple_SET_ITEM(tuple, count - begin, PyLong_FromLong(array[count]));
1170                         }
1171                         break;
1172                 }
1173         }
1174
1175         return tuple;
1176 }
1177 /* sequence slice (set): idparr[a:b] = value */
1178 static int BPy_IDArray_ass_slice(BPy_IDArray *self, int begin, int end, PyObject *seq)
1179 {
1180         IDProperty *prop = self->prop;
1181         short is_double = 0;
1182         const PyTypeObject *py_type = idp_array_py_type(self, &is_double);
1183         const size_t elem_size = is_double ? sizeof(double) : sizeof(float);
1184         size_t alloc_len;
1185         size_t size;
1186         void *vec;
1187
1188         CLAMP(begin, 0, prop->len);
1189         CLAMP(end, 0, prop->len);
1190         begin = MIN2(begin, end);
1191
1192         size = (end - begin);
1193         alloc_len = size * elem_size;
1194
1195         vec = MEM_mallocN(alloc_len, "array assignment"); /* NOTE: we count on int/float being the same size here */
1196         if (PyC_AsArray(vec, seq, size, py_type, is_double, "slice assignment: ") == -1) {
1197                 MEM_freeN(vec);
1198                 return -1;
1199         }
1200
1201         memcpy((void *)(((char *)IDP_Array(prop)) + (begin * elem_size)), vec, alloc_len);
1202
1203         MEM_freeN(vec);
1204         return 0;
1205 }
1206
1207 static PyObject *BPy_IDArray_subscript(BPy_IDArray *self, PyObject *item)
1208 {
1209         if (PyIndex_Check(item)) {
1210                 Py_ssize_t i;
1211                 i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1212                 if (i == -1 && PyErr_Occurred())
1213                         return NULL;
1214                 if (i < 0)
1215                         i += self->prop->len;
1216                 return BPy_IDArray_GetItem(self, i);
1217         }
1218         else if (PySlice_Check(item)) {
1219                 Py_ssize_t start, stop, step, slicelength;
1220
1221                 if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0)
1222                         return NULL;
1223
1224                 if (slicelength <= 0) {
1225                         return PyTuple_New(0);
1226                 }
1227                 else if (step == 1) {
1228                         return BPy_IDArray_slice(self, start, stop);
1229                 }
1230                 else {
1231                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
1232                         return NULL;
1233                 }
1234         }
1235         else {
1236                 PyErr_Format(PyExc_TypeError,
1237                              "vector indices must be integers, not %.200s",
1238                              __func__, Py_TYPE(item)->tp_name);
1239                 return NULL;
1240         }
1241 }
1242
1243 static int BPy_IDArray_ass_subscript(BPy_IDArray *self, PyObject *item, PyObject *value)
1244 {
1245         if (PyIndex_Check(item)) {
1246                 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
1247                 if (i == -1 && PyErr_Occurred())
1248                         return -1;
1249                 if (i < 0)
1250                         i += self->prop->len;
1251                 return BPy_IDArray_SetItem(self, i, value);
1252         }
1253         else if (PySlice_Check(item)) {
1254                 Py_ssize_t start, stop, step, slicelength;
1255
1256                 if (PySlice_GetIndicesEx(item, self->prop->len, &start, &stop, &step, &slicelength) < 0)
1257                         return -1;
1258
1259                 if (step == 1)
1260                         return BPy_IDArray_ass_slice(self, start, stop, value);
1261                 else {
1262                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with vectors");
1263                         return -1;
1264                 }
1265         }
1266         else {
1267                 PyErr_Format(PyExc_TypeError,
1268                              "vector indices must be integers, not %.200s",
1269                              Py_TYPE(item)->tp_name);
1270                 return -1;
1271         }
1272 }
1273
1274 static PyMappingMethods BPy_IDArray_AsMapping = {
1275         (lenfunc)BPy_IDArray_Len,
1276         (binaryfunc)BPy_IDArray_subscript,
1277         (objobjargproc)BPy_IDArray_ass_subscript
1278 };
1279
1280
1281 PyTypeObject BPy_IDArray_Type = {
1282         PyVarObject_HEAD_INIT(NULL, 0)
1283         /*  For printing, in format "<module>.<name>" */
1284         "IDPropertyArray",           /* char *tp_name; */
1285         sizeof(BPy_IDArray),       /* int tp_basicsize; */
1286         0,                          /* tp_itemsize;  For allocation */
1287
1288         /* Methods to implement standard operations */
1289
1290         NULL,                       /* destructor tp_dealloc; */
1291         NULL,                       /* printfunc tp_print; */
1292         NULL,     /* getattrfunc tp_getattr; */
1293         NULL,     /* setattrfunc tp_setattr; */
1294         NULL,                       /* cmpfunc tp_compare; */
1295         (reprfunc)BPy_IDArray_repr,     /* reprfunc tp_repr; */
1296
1297         /* Method suites for standard classes */
1298
1299         NULL,                       /* PyNumberMethods *tp_as_number; */
1300         &BPy_IDArray_Seq,           /* PySequenceMethods *tp_as_sequence; */
1301         &BPy_IDArray_AsMapping,     /* PyMappingMethods *tp_as_mapping; */
1302
1303         /* More standard operations (here for binary compatibility) */
1304
1305         NULL,                       /* hashfunc tp_hash; */
1306         NULL,                       /* ternaryfunc tp_call; */
1307         NULL,                       /* reprfunc tp_str; */
1308         NULL,                       /* getattrofunc tp_getattro; */
1309         NULL,                       /* setattrofunc tp_setattro; */
1310
1311         /* Functions to access object as input/output buffer */
1312         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1313
1314         /*** Flags to define presence of optional/expanded features ***/
1315         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
1316
1317         NULL,                       /*  char *tp_doc;  Documentation string */
1318         /*** Assigned meaning in release 2.0 ***/
1319         /* call function for all accessible objects */
1320         NULL,                       /* traverseproc tp_traverse; */
1321
1322         /* delete references to contained objects */
1323         NULL,                       /* inquiry tp_clear; */
1324
1325         /***  Assigned meaning in release 2.1 ***/
1326         /*** rich comparisons ***/
1327         NULL,                       /* richcmpfunc tp_richcompare; */
1328
1329         /***  weak reference enabler ***/
1330         0,                          /* long tp_weaklistoffset; */
1331
1332         /*** Added in release 2.2 ***/
1333         /*   Iterators */
1334         NULL,                       /* getiterfunc tp_iter; */
1335         NULL,                       /* iternextfunc tp_iternext; */
1336
1337         /*** Attribute descriptor and subclassing stuff ***/
1338         BPy_IDArray_methods,        /* struct PyMethodDef *tp_methods; */
1339         NULL,                       /* struct PyMemberDef *tp_members; */
1340         BPy_IDArray_getseters,       /* struct PyGetSetDef *tp_getset; */
1341         NULL,                       /* struct _typeobject *tp_base; */
1342         NULL,                       /* PyObject *tp_dict; */
1343         NULL,                       /* descrgetfunc tp_descr_get; */
1344         NULL,                       /* descrsetfunc tp_descr_set; */
1345         0,                          /* long tp_dictoffset; */
1346         NULL,                       /* initproc tp_init; */
1347         NULL,                       /* allocfunc tp_alloc; */
1348         NULL,                       /* newfunc tp_new; */
1349         /*  Low-level free-memory routine */
1350         NULL,                       /* freefunc tp_free;  */
1351         /* For PyObject_IS_GC */
1352         NULL,                       /* inquiry tp_is_gc;  */
1353         NULL,                       /* PyObject *tp_bases; */
1354         /* method resolution order */
1355         NULL,                       /* PyObject *tp_mro;  */
1356         NULL,                       /* PyObject *tp_cache; */
1357         NULL,                       /* PyObject *tp_subclasses; */
1358         NULL,                       /* PyObject *tp_weaklist; */
1359         NULL
1360 };
1361
1362 /*********** ID Property Group iterator ********/
1363
1364 static PyObject *IDGroup_Iter_repr(BPy_IDGroup_Iter *self)
1365 {
1366         return PyUnicode_FromFormat("(ID Property Group Iter \"%s\")", self->group->prop->name);
1367 }
1368
1369 static PyObject *BPy_Group_Iter_Next(BPy_IDGroup_Iter *self)
1370 {
1371
1372         if (self->cur) {
1373                 PyObject *ret;
1374                 IDProperty *cur;
1375
1376                 cur = self->cur;
1377                 self->cur = self->cur->next;
1378
1379                 if (self->mode == IDPROP_ITER_ITEMS) {
1380                         ret = PyTuple_New(2);
1381                         PyTuple_SET_ITEM(ret, 0, PyUnicode_FromString(cur->name));
1382                         PyTuple_SET_ITEM(ret, 1, BPy_IDGroup_WrapData(self->group->id, cur, self->group->prop));
1383                         return ret;
1384                 }
1385                 else {
1386                         return PyUnicode_FromString(cur->name);
1387                 }
1388         }
1389         else {
1390                 PyErr_SetString(PyExc_StopIteration, "iterator at end");
1391                 return NULL;
1392         }
1393 }
1394
1395 PyTypeObject BPy_IDGroup_Iter_Type = {
1396         PyVarObject_HEAD_INIT(NULL, 0)
1397         /*  For printing, in format "<module>.<name>" */
1398         "IDPropertyGroupIter",           /* char *tp_name; */
1399         sizeof(BPy_IDGroup_Iter),       /* int tp_basicsize; */
1400         0,                          /* tp_itemsize;  For allocation */
1401
1402         /* Methods to implement standard operations */
1403
1404         NULL,                       /* destructor tp_dealloc; */
1405         NULL,                       /* printfunc tp_print; */
1406         NULL,     /* getattrfunc tp_getattr; */
1407         NULL,     /* setattrfunc tp_setattr; */
1408         NULL,                       /* cmpfunc tp_compare; */
1409         (reprfunc) IDGroup_Iter_repr,     /* reprfunc tp_repr; */
1410
1411         /* Method suites for standard classes */
1412
1413         NULL,                       /* PyNumberMethods *tp_as_number; */
1414         NULL,                       /* PySequenceMethods *tp_as_sequence; */
1415         NULL,                       /* PyMappingMethods *tp_as_mapping; */
1416
1417         /* More standard operations (here for binary compatibility) */
1418
1419         NULL,                       /* hashfunc tp_hash; */
1420         NULL,                       /* ternaryfunc tp_call; */
1421         NULL,                       /* reprfunc tp_str; */
1422         NULL,                       /* getattrofunc tp_getattro; */
1423         NULL,                       /* setattrofunc tp_setattro; */
1424
1425         /* Functions to access object as input/output buffer */
1426         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1427
1428         /*** Flags to define presence of optional/expanded features ***/
1429         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
1430
1431         NULL,                       /*  char *tp_doc;  Documentation string */
1432         /*** Assigned meaning in release 2.0 ***/
1433         /* call function for all accessible objects */
1434         NULL,                       /* traverseproc tp_traverse; */
1435
1436         /* delete references to contained objects */
1437         NULL,                       /* inquiry tp_clear; */
1438
1439         /***  Assigned meaning in release 2.1 ***/
1440         /*** rich comparisons ***/
1441         NULL,                       /* richcmpfunc tp_richcompare; */
1442
1443         /***  weak reference enabler ***/
1444         0,                          /* long tp_weaklistoffset; */
1445
1446         /*** Added in release 2.2 ***/
1447         /*   Iterators */
1448         PyObject_SelfIter,                  /* getiterfunc tp_iter; */
1449         (iternextfunc) BPy_Group_Iter_Next, /* iternextfunc tp_iternext; */
1450 };
1451
1452 void IDProp_Init_Types(void)
1453 {
1454         PyType_Ready(&BPy_IDGroup_Type);
1455         PyType_Ready(&BPy_IDGroup_Iter_Type);
1456         PyType_Ready(&BPy_IDArray_Type);
1457 }
1458
1459 /*----------------------------MODULE INIT-------------------------*/
1460
1461 /* --- */
1462
1463 static struct PyModuleDef IDProp_types_module_def = {
1464         PyModuleDef_HEAD_INIT,
1465         "idprop.types",  /* m_name */
1466         NULL,  /* m_doc */
1467         0,  /* m_size */
1468         NULL,  /* m_methods */
1469         NULL,  /* m_reload */
1470         NULL,  /* m_traverse */
1471         NULL,  /* m_clear */
1472         NULL,  /* m_free */
1473 };
1474
1475 static PyObject *BPyInit_idprop_types(void)
1476 {
1477         PyObject *submodule;
1478
1479         submodule = PyModule_Create(&IDProp_types_module_def);
1480
1481         IDProp_Init_Types();
1482
1483 #define MODULE_TYPE_ADD(s, t) \
1484         PyModule_AddObject(s, t.tp_name, (PyObject *)&t); Py_INCREF((PyObject *)&t)
1485
1486         /* bmesh_py_types.c */
1487         MODULE_TYPE_ADD(submodule, BPy_IDGroup_Type);
1488         MODULE_TYPE_ADD(submodule, BPy_IDGroup_Iter_Type);
1489         MODULE_TYPE_ADD(submodule, BPy_IDArray_Type);
1490
1491 #undef MODULE_TYPE_ADD
1492
1493         return submodule;
1494 }
1495
1496 /* --- */
1497
1498 static PyMethodDef IDProp_methods[] = {
1499         {NULL, NULL, 0, NULL}
1500 };
1501
1502
1503 PyDoc_STRVAR(IDProp_module_doc,
1504 "This module provides access id property types (currently mainly for docs)."
1505 );
1506 static struct PyModuleDef IDProp_module_def = {
1507         PyModuleDef_HEAD_INIT,
1508         "idprop",  /* m_name */
1509         IDProp_module_doc,  /* m_doc */
1510         0,  /* m_size */
1511         IDProp_methods,  /* m_methods */
1512         NULL,  /* m_reload */
1513         NULL,  /* m_traverse */
1514         NULL,  /* m_clear */
1515         NULL,  /* m_free */
1516 };
1517
1518 PyObject *BPyInit_idprop(void)
1519 {
1520         PyObject *mod;
1521         PyObject *submodule;
1522         PyObject *sys_modules = PyThreadState_GET()->interp->modules;
1523
1524         mod = PyModule_Create(&IDProp_module_def);
1525
1526         /* idprop.types */
1527         PyModule_AddObject(mod, "types", (submodule = BPyInit_idprop_types()));
1528         PyDict_SetItemString(sys_modules, PyModule_GetName(submodule), submodule);
1529         Py_INCREF(submodule);
1530
1531         return mod;
1532 }
1533
1534
1535 #ifdef DEBUG
1536 /* -------------------------------------------------------------------- */
1537 /* debug only function */
1538
1539 void IDP_spit(IDProperty *prop)
1540 {
1541         if (prop) {
1542                 PyGILState_STATE gilstate;
1543                 int use_gil = TRUE; /* !PyC_IsInterpreterActive(); */
1544                 PyObject *ret_dict;
1545                 PyObject *ret_str;
1546
1547                 if (use_gil) {
1548                         gilstate = PyGILState_Ensure();
1549                 }
1550
1551                 /* to_dict() */
1552                 ret_dict = BPy_IDGroup_MapDataToPy(prop);
1553                 ret_str = PyObject_Repr(ret_dict);
1554                 Py_DECREF(ret_dict);
1555
1556                 printf("IDProperty(%p): %s\n", prop, _PyUnicode_AsString(ret_str));
1557
1558                 Py_DECREF(ret_str);
1559
1560                 if (use_gil) {
1561                         PyGILState_Release(gilstate);
1562                 }
1563         }
1564         else {
1565                 printf("IDProperty: <NIL>\n");
1566         }
1567 }
1568
1569 #endif