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