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