converted more mixed tab/space indentations to tabs. only whitespace changes.
[blender.git] / source / blender / python / generic / IDProp.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  *
21  * Contributor(s): Joseph Eagar, Campbell Barton
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/python/generic/IDProp.c
27  *  \ingroup pygen
28  */
29
30
31 #include <Python.h>
32
33 #include "IDProp.h"
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_string.h"
37 #include "BLI_utildefines.h"
38
39 #include "BKE_idprop.h"
40
41
42 #define USE_STRING_COERCE
43
44 #ifdef USE_STRING_COERCE
45 #include "py_capi_utils.h"
46 #endif
47
48 PyObject *              PyC_UnicodeFromByte(const char *str);
49 const char *    PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce); /* coerce must be NULL */
50
51 /*** Function to wrap ID properties ***/
52 PyObject *BPy_Wrap_IDProperty(ID *id, IDProperty *prop, IDProperty *parent);
53
54 extern PyTypeObject IDArray_Type;
55 extern PyTypeObject IDGroup_Iter_Type;
56
57 /*********************** ID Property Main Wrapper Stuff ***************/
58
59 static PyObject *IDGroup_repr( BPy_IDProperty *self )
60 {
61         return PyUnicode_FromFormat( "<bpy ID property from \"%s\">", self->id->name);
62 }
63
64 extern PyTypeObject IDGroup_Type;
65
66 PyObject *BPy_IDGroup_WrapData( ID *id, IDProperty *prop )
67 {
68         switch ( prop->type ) {
69                 case IDP_STRING:
70 #ifdef USE_STRING_COERCE
71                         return PyC_UnicodeFromByte(prop->data.pointer);
72 #else
73                         return PyUnicode_FromString(prop->data.pointer);
74 #endif
75                 case IDP_INT:
76                         return PyLong_FromLong( (long)prop->data.val );
77                 case IDP_FLOAT:
78                         return PyFloat_FromDouble( (double)(*(float*)(&prop->data.val)) );
79                 case IDP_DOUBLE:
80                         return PyFloat_FromDouble( (*(double*)(&prop->data.val)) );
81                 case IDP_GROUP:
82                         /*blegh*/
83                         {
84                                 BPy_IDProperty *group = PyObject_New(BPy_IDProperty, &IDGroup_Type);
85                                 group->id = id;
86                                 group->prop = prop;
87                                 return (PyObject*) group;
88                         }
89                 case IDP_ARRAY:
90                         {
91                                 BPy_IDProperty *array = PyObject_New(BPy_IDProperty, &IDArray_Type);
92                                 array->id = id;
93                                 array->prop = prop;
94                                 return (PyObject*) array;
95                         }
96                 case IDP_IDPARRAY: /* this could be better a internal type */
97                         {
98                                 PyObject *seq = PyList_New(prop->len), *wrap;
99                                 IDProperty *array= IDP_IDPArray(prop);
100                                 int i;
101
102                                 if (!seq) {
103                                         PyErr_Format(PyExc_RuntimeError, "BPy_IDGroup_MapDataToPy, IDP_IDPARRAY: PyList_New(%d) failed", prop->len);
104                                         return NULL;
105                                 }
106
107                                 for (i=0; i<prop->len; i++) {
108                                         wrap= BPy_IDGroup_WrapData(id, array++);
109
110                                         if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
111                                                 return NULL;
112
113                                         PyList_SET_ITEM(seq, i, wrap);
114                                 }
115
116                                 return seq;
117                         }
118                 /* case IDP_IDPARRAY: TODO */
119         }
120         Py_RETURN_NONE;
121 }
122
123 #if 0 /* UNUSED, currenly assignment overwrites into new properties, rather then setting in-place */
124 static int BPy_IDGroup_SetData(BPy_IDProperty *self, IDProperty *prop, PyObject *value)
125 {
126         switch (prop->type) {
127                 case IDP_STRING:
128                 {
129                         char *st;
130                         if (!PyUnicode_Check(value)) {
131                                 PyErr_SetString(PyExc_TypeError, "expected a string!");
132                                 return -1;
133                         }
134 #ifdef USE_STRING_COERCE
135                         {
136                                 int alloc_len;
137                                 PyObject *value_coerce= NULL;
138
139                                 st= (char *)PyC_UnicodeAsByte(value, &value_coerce);
140                                 alloc_len= strlen(st) + 1;
141
142                                 st = _PyUnicode_AsString(value);
143                                 IDP_ResizeArray(prop, alloc_len);
144                                 memcpy(prop->data.pointer, st, alloc_len);
145                                 Py_XDECREF(value_coerce);
146                         }
147 #else
148                         st = _PyUnicode_AsString(value);
149                         IDP_ResizeArray(prop, strlen(st)+1);
150                         strcpy(prop->data.pointer, st);
151 #endif
152
153                         return 0;
154                 }
155
156                 case IDP_INT:
157                 {
158                         int ivalue= PyLong_AsSsize_t(value);
159                         if (ivalue==-1 && PyErr_Occurred()) {
160                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
161                                 return -1;
162                         }
163                         prop->data.val = ivalue;
164                         break;
165                 }
166                 case IDP_FLOAT:
167                 {
168                         float fvalue= (float)PyFloat_AsDouble(value);
169                         if (fvalue==-1 && PyErr_Occurred()) {
170                                 PyErr_SetString(PyExc_TypeError, "expected a float");
171                                 return -1;
172                         }
173                         *(float*)&self->prop->data.val = fvalue;
174                         break;
175                 }
176                 case IDP_DOUBLE:
177                 {
178                         double dvalue= PyFloat_AsDouble(value);
179                         if (dvalue==-1 && PyErr_Occurred()) {
180                                 PyErr_SetString(PyExc_TypeError, "expected a float");
181                                 return -1;
182                         }
183                         *(double*)&self->prop->data.val = dvalue;
184                         break;
185                 }
186                 default:
187                         PyErr_SetString(PyExc_AttributeError, "attempt to set read-only attribute!");
188                         return -1;
189         }
190         return 0;
191 }
192 #endif
193
194 static PyObject *BPy_IDGroup_GetName(BPy_IDProperty *self, void *UNUSED(closure))
195 {
196         return PyUnicode_FromString(self->prop->name);
197 }
198
199 static int BPy_IDGroup_SetName(BPy_IDProperty *self, PyObject *value, void *UNUSED(closure))
200 {
201         char *st;
202         if (!PyUnicode_Check(value)) {
203                 PyErr_SetString(PyExc_TypeError, "expected a string!");
204                 return -1;
205         }
206
207         st = _PyUnicode_AsString(value);
208         if (BLI_strnlen(st, MAX_IDPROP_NAME) == MAX_IDPROP_NAME) {
209                 PyErr_SetString(PyExc_TypeError, "string length cannot exceed 31 characters!");
210                 return -1;
211         }
212
213         BLI_strncpy(self->prop->name, st, sizeof(self->prop->name));
214         return 0;
215 }
216
217 #if 0
218 static PyObject *BPy_IDGroup_GetType(BPy_IDProperty *self)
219 {
220         return PyLong_FromSsize_t(self->prop->type);
221 }
222 #endif
223
224 static PyGetSetDef BPy_IDGroup_getseters[] = {
225         {(char *)"name", (getter)BPy_IDGroup_GetName, (setter)BPy_IDGroup_SetName, (char *)"The name of this Group.", NULL},
226          {NULL, NULL, NULL, NULL, NULL}
227 };
228
229 static Py_ssize_t BPy_IDGroup_Map_Len(BPy_IDProperty *self)
230 {
231         if (self->prop->type != IDP_GROUP) {
232                 PyErr_SetString(PyExc_TypeError, "len() of unsized object");
233                 return -1;
234         }
235
236         return self->prop->len;
237 }
238
239 static PyObject *BPy_IDGroup_Map_GetItem(BPy_IDProperty *self, PyObject *item)
240 {
241         IDProperty *idprop;
242         char *name;
243
244         if (self->prop->type  != IDP_GROUP) {
245                 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
246                 return NULL;
247         }
248
249         name= _PyUnicode_AsString(item);
250
251         if (name == NULL) {
252                 PyErr_SetString(PyExc_TypeError, "only strings are allowed as keys of ID properties");
253                 return NULL;
254         }
255
256         idprop= IDP_GetPropertyFromGroup(self->prop, name);
257
258         if(idprop==NULL) {
259                 PyErr_SetString(PyExc_KeyError, "key not in subgroup dict");
260                 return NULL;
261         }
262
263         return BPy_IDGroup_WrapData(self->id, idprop);
264
265 }
266
267 /*returns NULL on success, error string on failure*/
268 static int idp_sequence_type(PyObject *seq)
269 {
270         PyObject *item;
271         int type= IDP_INT;
272
273         int i, len = PySequence_Size(seq);
274         for (i=0; i < len; i++) {
275                 item = PySequence_GetItem(seq, i);
276                 if (PyFloat_Check(item)) {
277                         if(type == IDP_IDPARRAY) { /* mixed dict/int */
278                                 Py_DECREF(item);
279                                 return -1;
280                         }
281                         type= IDP_DOUBLE;
282                 }
283                 else if (PyLong_Check(item)) {
284                         if(type == IDP_IDPARRAY) { /* mixed dict/int */
285                                 Py_DECREF(item);
286                                 return -1;
287                         }
288                 }
289                 else if (PyMapping_Check(item)) {
290                         if(i != 0 && (type != IDP_IDPARRAY)) { /* mixed dict/int */
291                                 Py_DECREF(item);
292                                 return -1;
293                         }
294                         type= IDP_IDPARRAY;
295                 }
296                 else {
297                         Py_XDECREF(item);
298                         return -1;
299                 }
300
301                 Py_DECREF(item);
302         }
303
304         return type;
305 }
306
307 /* note: group can be a pointer array or a group */
308 const char *BPy_IDProperty_Map_ValidateAndCreate(const char *name, IDProperty *group, PyObject *ob)
309 {
310         IDProperty *prop = NULL;
311         IDPropertyTemplate val = {0};
312
313         if(strlen(name) >= sizeof(group->name))
314                 return "the length of IDProperty names is limited to 31 characters";
315
316         if (PyFloat_Check(ob)) {
317                 val.d = PyFloat_AsDouble(ob);
318                 prop = IDP_New(IDP_DOUBLE, val, name);
319         }
320         else if (PyLong_Check(ob)) {
321                 val.i = (int) PyLong_AsSsize_t(ob);
322                 prop = IDP_New(IDP_INT, val, name);
323         }
324         else if (PyUnicode_Check(ob)) {
325 #ifdef USE_STRING_COERCE
326                 PyObject *value_coerce= NULL;
327                 val.str = (char *)PyC_UnicodeAsByte(ob, &value_coerce);
328                 prop = IDP_New(IDP_STRING, val, name);
329                 Py_XDECREF(value_coerce);
330 #else
331                 val.str = _PyUnicode_AsString(ob);
332                 prop = IDP_New(IDP_STRING, val, name);
333 #endif
334         }
335         else if (PySequence_Check(ob)) {
336                 PyObject *item;
337                 int i;
338
339                 if((val.array.type= idp_sequence_type(ob)) == -1)
340                         return "only floats, ints and dicts are allowed in ID property arrays";
341
342                 /*validate sequence and derive type.
343                 we assume IDP_INT unless we hit a float
344                 number; then we assume it's */
345
346                 val.array.len = PySequence_Size(ob);
347
348                 switch(val.array.type) {
349                 case IDP_DOUBLE:
350                         prop = IDP_New(IDP_ARRAY, val, name);
351                         for (i=0; i<val.array.len; i++) {
352                                 item = PySequence_GetItem(ob, i);
353                                 ((double*)prop->data.pointer)[i] = (float)PyFloat_AsDouble(item);
354                                 Py_DECREF(item);
355                         }
356                         break;
357                 case IDP_INT:
358                         prop = IDP_New(IDP_ARRAY, val, name);
359                         for (i=0; i<val.array.len; i++) {
360                                 item = PySequence_GetItem(ob, i);
361                                 ((int*)prop->data.pointer)[i] = (int)PyLong_AsSsize_t(item);
362                                 Py_DECREF(item);
363                         }
364                         break;
365                 case IDP_IDPARRAY:
366                         prop= IDP_NewIDPArray(name);
367                         for (i=0; i<val.array.len; i++) {
368                                 const char *error;
369                                 item = PySequence_GetItem(ob, i);
370                                 error= BPy_IDProperty_Map_ValidateAndCreate("", prop, item);
371                                 Py_DECREF(item);
372
373                                 if(error)
374                                         return error;
375                         }
376                         break;
377                 }
378         }
379         else if (PyMapping_Check(ob)) {
380                 PyObject *keys, *vals, *key, *pval;
381                 int i, len;
382                 /*yay! we get into recursive stuff now!*/
383                 keys = PyMapping_Keys(ob);
384                 vals = PyMapping_Values(ob);
385
386                 /*we allocate the group first; if we hit any invalid data,
387                   we can delete it easily enough.*/
388                 prop = IDP_New(IDP_GROUP, val, name);
389                 len = PyMapping_Length(ob);
390                 for (i=0; i<len; i++) {
391                         key = PySequence_GetItem(keys, i);
392                         pval = PySequence_GetItem(vals, i);
393                         if (!PyUnicode_Check(key)) {
394                                 IDP_FreeProperty(prop);
395                                 MEM_freeN(prop);
396                                 Py_XDECREF(keys);
397                                 Py_XDECREF(vals);
398                                 Py_XDECREF(key);
399                                 Py_XDECREF(pval);
400                                 return "invalid element in subgroup dict template!";
401                         }
402                         if (BPy_IDProperty_Map_ValidateAndCreate(_PyUnicode_AsString(key), prop, pval)) {
403                                 IDP_FreeProperty(prop);
404                                 MEM_freeN(prop);
405                                 Py_XDECREF(keys);
406                                 Py_XDECREF(vals);
407                                 Py_XDECREF(key);
408                                 Py_XDECREF(pval);
409                                 return "invalid element in subgroup dict template!";
410                         }
411                         Py_XDECREF(key);
412                         Py_XDECREF(pval);
413                 }
414                 Py_XDECREF(keys);
415                 Py_XDECREF(vals);
416         }
417         else return "invalid property value";
418
419         if(group->type==IDP_IDPARRAY) {
420                 IDP_AppendArray(group, prop);
421                 // IDP_FreeProperty(item); // IDP_AppendArray does a shallow copy (memcpy), only free memory
422                 MEM_freeN(prop);
423         }
424         else {
425                 IDP_ReplaceInGroup(group, prop);
426         }
427
428         return NULL;
429 }
430
431 int BPy_Wrap_SetMapItem(IDProperty *prop, PyObject *key, PyObject *val)
432 {
433         if (prop->type  != IDP_GROUP) {
434                 PyErr_SetString(PyExc_TypeError, "unsubscriptable object");
435                 return -1;
436         }
437
438         if (val == NULL) { /* del idprop[key] */
439                 IDProperty *pkey = IDP_GetPropertyFromGroup(prop, _PyUnicode_AsString(key));
440                 if (pkey) {
441                         IDP_RemFromGroup(prop, pkey);
442                         IDP_FreeProperty(pkey);
443                         MEM_freeN(pkey);
444                         return 0;
445                 }
446                 else {
447                         PyErr_SetString(PyExc_KeyError, "property not found in group");
448                         return -1;
449                 }
450         }
451         else {
452                 const char *err;
453
454                 if (!PyUnicode_Check(key)) {
455                         PyErr_SetString(PyExc_TypeError, "only strings are allowed as subgroup keys");
456                         return -1;
457                 }
458
459                 err = BPy_IDProperty_Map_ValidateAndCreate(_PyUnicode_AsString(key), prop, val);
460                 if (err) {
461                         PyErr_SetString(PyExc_KeyError, err );
462                         return -1;
463                 }
464
465                 return 0;
466         }
467 }
468
469 static int BPy_IDGroup_Map_SetItem(BPy_IDProperty *self, PyObject *key, PyObject *val)
470 {
471         return BPy_Wrap_SetMapItem(self->prop, key, val);
472 }
473
474 static PyObject *BPy_IDGroup_SpawnIterator(BPy_IDProperty *self)
475 {
476         BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &IDGroup_Iter_Type);
477         iter->group = self;
478         iter->mode = IDPROP_ITER_KEYS;
479         iter->cur = self->prop->data.group.first;
480         Py_XINCREF(iter);
481         return (PyObject*) iter;
482 }
483
484 static PyObject *BPy_IDGroup_MapDataToPy(IDProperty *prop)
485 {
486         switch (prop->type) {
487                 case IDP_STRING:
488 #ifdef USE_STRING_COERCE
489                         return PyC_UnicodeFromByte(prop->data.pointer);
490 #else
491                         return PyUnicode_FromString(prop->data.pointer);
492 #endif
493                         break;
494                 case IDP_FLOAT:
495                         return PyFloat_FromDouble(*((float*)&prop->data.val));
496                         break;
497                 case IDP_DOUBLE:
498                         return PyFloat_FromDouble(*((double*)&prop->data.val));
499                         break;
500                 case IDP_INT:
501                         return PyLong_FromSsize_t( prop->data.val );
502                         break;
503                 case IDP_ARRAY:
504                 {
505                         PyObject *seq = PyList_New(prop->len);
506                         int i;
507
508                         if (!seq) {
509                                 PyErr_Format(PyExc_RuntimeError, "BPy_IDGroup_MapDataToPy, IDP_ARRAY: PyList_New(%d) failed", prop->len);
510                                 return NULL;
511                         }
512
513                         for (i=0; i<prop->len; i++) {
514                                 if (prop->subtype == IDP_FLOAT) {
515                                         PyList_SET_ITEM(seq, i,
516                                                         PyFloat_FromDouble(((float*)prop->data.pointer)[i]));
517                                 }
518                                 else if (prop->subtype == IDP_DOUBLE) {
519                                         PyList_SET_ITEM(seq, i,
520                                                         PyFloat_FromDouble(((double*)prop->data.pointer)[i]));
521                                 }
522                                 else    {
523                                         PyList_SET_ITEM(seq, i,
524                                                         PyLong_FromLong(((int*)prop->data.pointer)[i]));
525                                 }
526                         }
527                         return seq;
528                 }
529                 case IDP_IDPARRAY:
530                 {
531                         PyObject *seq = PyList_New(prop->len), *wrap;
532                         IDProperty *array= IDP_IDPArray(prop);
533                         int i;
534
535                         if (!seq) {
536                                 PyErr_Format(PyExc_RuntimeError, "BPy_IDGroup_MapDataToPy, IDP_IDPARRAY: PyList_New(%d) failed", prop->len);
537                                 return NULL;
538                         }
539
540                         for (i=0; i<prop->len; i++) {
541                                 wrap= BPy_IDGroup_MapDataToPy(array++);
542
543                                 if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
544                                         return NULL;
545
546                                 PyList_SET_ITEM(seq, i, wrap);
547                         }
548                         return seq;
549                 }
550                 case IDP_GROUP:
551                 {
552                         PyObject *dict = PyDict_New(), *wrap;
553                         IDProperty *loop;
554
555                         for (loop=prop->data.group.first; loop; loop=loop->next) {
556                                 wrap = BPy_IDGroup_MapDataToPy(loop);
557
558                                 if (!wrap) /* BPy_IDGroup_MapDataToPy sets the error */
559                                         return NULL;
560
561                                 PyDict_SetItemString(dict, loop->name, wrap);
562                         }
563                         return dict;
564                 }
565         }
566
567         PyErr_Format(PyExc_RuntimeError, "eek!! '%s' property exists with a bad type code '%d' !!!", prop->name, prop->type);
568         return NULL;
569 }
570
571 static PyObject *BPy_IDGroup_Pop(BPy_IDProperty *self, PyObject *value)
572 {
573         IDProperty *idprop;
574         PyObject *pyform;
575         char *name = _PyUnicode_AsString(value);
576
577         if (!name) {
578                 PyErr_SetString(PyExc_TypeError, "pop expected at least 1 argument, got 0");
579                 return NULL;
580         }
581
582         idprop= IDP_GetPropertyFromGroup(self->prop, name);
583
584         if(idprop) {
585                 pyform = BPy_IDGroup_MapDataToPy(idprop);
586
587                 if (!pyform) {
588                         /*ok something bad happened with the pyobject,
589                           so don't remove the prop from the group.  if pyform is
590                           NULL, then it already should have raised an exception.*/
591                         return NULL;
592                 }
593
594                 IDP_RemFromGroup(self->prop, idprop);
595                 return pyform;
596         }
597
598         PyErr_SetString(PyExc_KeyError, "item not in group");
599         return NULL;
600 }
601
602 static PyObject *BPy_IDGroup_IterItems(BPy_IDProperty *self)
603 {
604         BPy_IDGroup_Iter *iter = PyObject_New(BPy_IDGroup_Iter, &IDGroup_Iter_Type);
605         iter->group = self;
606         iter->mode = IDPROP_ITER_ITEMS;
607         iter->cur = self->prop->data.group.first;
608         Py_XINCREF(iter);
609         return (PyObject*) iter;
610 }
611
612 /* utility function */
613 static void BPy_IDGroup_CorrectListLen(IDProperty *prop, PyObject *seq, int len)
614 {
615         int j;
616
617         printf("ID Property Error found and corrected in BPy_IDGroup_GetKeys/Values/Items!\n");
618
619         /*fill rest of list with valid references to None*/
620         for (j=len; j<prop->len; j++) {
621                 Py_INCREF(Py_None);
622                 PyList_SET_ITEM(seq, j, Py_None);
623         }
624
625         /*set correct group length*/
626         prop->len = len;
627 }
628
629 PyObject *BPy_Wrap_GetKeys(IDProperty *prop)
630 {
631         PyObject *seq = PyList_New(prop->len);
632         IDProperty *loop;
633         int i;
634
635         for (i=0, loop=prop->data.group.first; loop && (i < prop->len); loop=loop->next, i++)
636                 PyList_SET_ITEM(seq, i, PyUnicode_FromString(loop->name));
637
638         /* if the id prop is corrupt, count the remaining */
639         for (; loop; loop=loop->next, i++) {}
640
641         if (i != prop->len) { /* if the loop didnt finish, we know the length is wrong */
642                 BPy_IDGroup_CorrectListLen(prop, seq, i);
643                 Py_DECREF(seq); /*free the list*/
644                 /*call self again*/
645                 return BPy_Wrap_GetKeys(prop);
646         }
647
648         return seq;
649 }
650
651 PyObject *BPy_Wrap_GetValues(ID *id, IDProperty *prop)
652 {
653         PyObject *seq = PyList_New(prop->len);
654         IDProperty *loop;
655         int i;
656
657         for (i=0, loop=prop->data.group.first; loop; loop=loop->next, i++) {
658                 PyList_SET_ITEM(seq, i, BPy_IDGroup_WrapData(id, loop));
659         }
660
661         if (i != prop->len) {
662                 BPy_IDGroup_CorrectListLen(prop, seq, i);
663                 Py_DECREF(seq); /*free the list*/
664                 /*call self again*/
665                 return BPy_Wrap_GetValues(id, prop);
666         }
667
668         return seq;
669 }
670
671 PyObject *BPy_Wrap_GetItems(ID *id, IDProperty *prop)
672 {
673         PyObject *seq = PyList_New(prop->len);
674         IDProperty *loop;
675         int i;
676
677         for (i=0, loop=prop->data.group.first; loop; loop=loop->next, i++) {
678                 PyObject *item= PyTuple_New(2);
679                 PyTuple_SET_ITEM(item, 0, PyUnicode_FromString(loop->name));
680                 PyTuple_SET_ITEM(item, 1, BPy_IDGroup_WrapData(id, loop));
681                 PyList_SET_ITEM(seq, i, item);
682         }
683
684         if (i != prop->len) {
685                 BPy_IDGroup_CorrectListLen(prop, seq, i);
686                 Py_DECREF(seq); /*free the list*/
687                 /*call self again*/
688                 return BPy_Wrap_GetItems(id, prop);
689         }
690
691         return seq;
692 }
693
694
695 static PyObject *BPy_IDGroup_GetKeys(BPy_IDProperty *self)
696 {
697         return BPy_Wrap_GetKeys(self->prop);
698 }
699
700 static PyObject *BPy_IDGroup_GetValues(BPy_IDProperty *self)
701 {
702         return BPy_Wrap_GetValues(self->id, self->prop);
703 }
704
705 static PyObject *BPy_IDGroup_GetItems(BPy_IDProperty *self)
706 {
707         return BPy_Wrap_GetItems(self->id, self->prop);
708 }
709
710 static int BPy_IDGroup_Contains(BPy_IDProperty *self, PyObject *value)
711 {
712         char *name = _PyUnicode_AsString(value);
713
714         if (!name) {
715                 PyErr_SetString(PyExc_TypeError, "expected a string");
716                 return -1;
717         }
718
719         return IDP_GetPropertyFromGroup(self->prop, name) ? 1:0;
720 }
721
722 static PyObject *BPy_IDGroup_Update(BPy_IDProperty *self, PyObject *value)
723 {
724         PyObject *pkey, *pval;
725         Py_ssize_t i=0;
726
727         if (!PyDict_Check(value)) {
728                 PyErr_SetString(PyExc_TypeError, "expected an object derived from dict");
729                 return NULL;
730         }
731
732         while (PyDict_Next(value, &i, &pkey, &pval)) {
733                 BPy_IDGroup_Map_SetItem(self, pkey, pval);
734                 if (PyErr_Occurred()) return NULL;
735         }
736
737         Py_RETURN_NONE;
738 }
739
740 static PyObject *BPy_IDGroup_ConvertToPy(BPy_IDProperty *self)
741 {
742         return BPy_IDGroup_MapDataToPy(self->prop);
743 }
744
745
746 /* Matches python dict.get(key, [default]) */
747 static PyObject* BPy_IDGroup_Get(BPy_IDProperty *self, PyObject *args)
748 {
749         IDProperty *idprop;
750         char *key;
751         PyObject* def = Py_None;
752
753         if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
754                 return NULL;
755
756         idprop= IDP_GetPropertyFromGroup(self->prop, key);
757         if (idprop) {
758                 PyObject* pyobj = BPy_IDGroup_WrapData(self->id, idprop);
759                 if (pyobj)
760                         return pyobj;
761         }
762
763         Py_INCREF(def);
764         return def;
765 }
766
767 static struct PyMethodDef BPy_IDGroup_methods[] = {
768         {"pop", (PyCFunction)BPy_IDGroup_Pop, METH_O,
769                 "pop an item from the group; raises KeyError if the item doesn't exist"},
770         {"iteritems", (PyCFunction)BPy_IDGroup_IterItems, METH_NOARGS,
771                 "iterate through the items in the dict; behaves like dictionary method iteritems"},
772         {"keys", (PyCFunction)BPy_IDGroup_GetKeys, METH_NOARGS,
773                 "get the keys associated with this group as a list of strings"},
774         {"values", (PyCFunction)BPy_IDGroup_GetValues, METH_NOARGS,
775                 "get the values associated with this group"},
776         {"items", (PyCFunction)BPy_IDGroup_GetItems, METH_NOARGS,
777                 "get the items associated with this group"},
778         {"update", (PyCFunction)BPy_IDGroup_Update, METH_O,
779                 "updates the values in the group with the values of another or a dict"},
780         {"get", (PyCFunction)BPy_IDGroup_Get, METH_VARARGS,
781                 "idprop.get(k[,d]) -> idprop[k] if k in idprop, else d.  d defaults to None"},
782         {"convert_to_pyobject", (PyCFunction)BPy_IDGroup_ConvertToPy, METH_NOARGS,
783                 "return a purely python version of the group"},
784         {NULL, NULL, 0, NULL}
785 };
786
787 static PySequenceMethods BPy_IDGroup_Seq = {
788         (lenfunc) BPy_IDGroup_Map_Len,          /* lenfunc sq_length */
789         NULL,                                                           /* binaryfunc sq_concat */
790         NULL,                                                           /* ssizeargfunc sq_repeat */
791         NULL,                                                           /* ssizeargfunc sq_item */ /* TODO - setting this will allow PySequence_Check to return True */
792         NULL,                                                           /* intintargfunc ***was_sq_slice*** */
793         NULL,                                                           /* intobjargproc sq_ass_item */
794         NULL,                                                           /* ssizeobjargproc ***was_sq_ass_slice*** */
795         (objobjproc) BPy_IDGroup_Contains,      /* objobjproc sq_contains */
796         NULL,                                                           /* binaryfunc sq_inplace_concat */
797         NULL,                                                           /* ssizeargfunc sq_inplace_repeat */
798 };
799
800 static PyMappingMethods BPy_IDGroup_Mapping = {
801         (lenfunc)BPy_IDGroup_Map_Len,                   /*inquiry mp_length */
802         (binaryfunc)BPy_IDGroup_Map_GetItem,            /*binaryfunc mp_subscript */
803         (objobjargproc)BPy_IDGroup_Map_SetItem, /*objobjargproc mp_ass_subscript */
804 };
805
806 PyTypeObject IDGroup_Type = {
807         PyVarObject_HEAD_INIT(NULL, 0)
808         /*  For printing, in format "<module>.<name>" */
809         "Blender IDProperty",           /* char *tp_name; */
810         sizeof( BPy_IDProperty ),       /* int tp_basicsize; */
811         0,                          /* tp_itemsize;  For allocation */
812
813         /* Methods to implement standard operations */
814
815         NULL,                                           /* destructor tp_dealloc; */
816         NULL,                       /* printfunc tp_print; */
817         NULL,     /* getattrfunc tp_getattr; */
818         NULL,     /* setattrfunc tp_setattr; */
819         NULL,                       /* cmpfunc tp_compare; */
820         ( reprfunc ) IDGroup_repr,     /* reprfunc tp_repr; */
821
822         /* Method suites for standard classes */
823
824         NULL,                       /* PyNumberMethods *tp_as_number; */
825         &BPy_IDGroup_Seq,                       /* PySequenceMethods *tp_as_sequence; */
826         &BPy_IDGroup_Mapping,           /* PyMappingMethods *tp_as_mapping; */
827
828         /* More standard operations (here for binary compatibility) */
829
830         NULL,                       /* hashfunc tp_hash; */
831         NULL,                       /* ternaryfunc tp_call; */
832         NULL,                       /* reprfunc tp_str; */
833         NULL,                       /* getattrofunc tp_getattro; */
834         NULL,                       /* setattrofunc tp_setattro; */
835
836         /* Functions to access object as input/output buffer */
837         NULL,                       /* PyBufferProcs *tp_as_buffer; */
838
839   /*** Flags to define presence of optional/expanded features ***/
840         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
841
842         NULL,                       /*  char *tp_doc;  Documentation string */
843   /*** Assigned meaning in release 2.0 ***/
844         /* call function for all accessible objects */
845         NULL,                       /* traverseproc tp_traverse; */
846
847         /* delete references to contained objects */
848         NULL,                       /* inquiry tp_clear; */
849
850   /***  Assigned meaning in release 2.1 ***/
851   /*** rich comparisons ***/
852         NULL,                       /* richcmpfunc tp_richcompare; */
853
854   /***  weak reference enabler ***/
855         0,                          /* long tp_weaklistoffset; */
856
857   /*** Added in release 2.2 ***/
858         /*   Iterators */
859         (getiterfunc)BPy_IDGroup_SpawnIterator, /* getiterfunc tp_iter; */
860         NULL,                       /* iternextfunc tp_iternext; */
861   /*** Attribute descriptor and subclassing stuff ***/
862         BPy_IDGroup_methods,        /* struct PyMethodDef *tp_methods; */
863         NULL,                       /* struct PyMemberDef *tp_members; */
864         BPy_IDGroup_getseters,       /* struct PyGetSetDef *tp_getset; */
865 };
866
867 /*********** Main external wrapping function *******/
868 PyObject *BPy_Wrap_IDProperty(ID *id, IDProperty *prop, IDProperty *parent)
869 {
870         BPy_IDProperty *wrap = PyObject_New(BPy_IDProperty, &IDGroup_Type);
871         wrap->prop = prop;
872         wrap->parent = parent;
873         wrap->id = id;
874         //wrap->destroy = 0;
875         return (PyObject*) wrap;
876 }
877
878
879 /********Array Wrapper********/
880
881 static PyObject *IDArray_repr(BPy_IDArray *self)
882 {
883         return PyUnicode_FromFormat("(ID Array [%d])", self->prop->len);
884 }
885
886
887 static PyObject *BPy_IDArray_GetType(BPy_IDArray *self)
888 {
889         return PyLong_FromSsize_t( self->prop->subtype );
890 }
891
892 static PyObject *BPy_IDArray_GetLen(BPy_IDArray *self)
893 {
894         return PyLong_FromSsize_t( self->prop->len );
895 }
896
897 static PyGetSetDef BPy_IDArray_getseters[] = {
898         {(char *)"len", (getter)BPy_IDArray_GetLen, (setter)NULL, (char *)"The length of the array, can also be gotten with len(array).", NULL},
899         {(char *)"type", (getter)BPy_IDArray_GetType, (setter)NULL, (char *)"The type of the data in the array, is an ant.", NULL},
900         {NULL, NULL, NULL, NULL, NULL},
901 };
902
903 static PyObject *BPy_IDArray_ConvertToPy(BPy_IDArray *self)
904 {
905         return BPy_IDGroup_MapDataToPy(self->prop);
906 }
907
908 static PyMethodDef BPy_IDArray_methods[] = {
909         {"convert_to_pyobject", (PyCFunction)BPy_IDArray_ConvertToPy, METH_NOARGS,
910                 "return a purely python version of the group"},
911         {NULL, NULL, 0, NULL}
912 };
913
914 static int BPy_IDArray_Len(BPy_IDArray *self)
915 {
916         return self->prop->len;
917 }
918
919 static PyObject *BPy_IDArray_GetItem(BPy_IDArray *self, int index)
920 {
921         if (index < 0 || index >= self->prop->len) {
922                 PyErr_SetString(PyExc_IndexError, "index out of range!");
923                 return NULL;
924         }
925
926         switch (self->prop->subtype) {
927                 case IDP_FLOAT:
928                         return PyFloat_FromDouble( (double)(((float*)self->prop->data.pointer)[index]));
929                         break;
930                 case IDP_DOUBLE:
931                         return PyFloat_FromDouble( (((double*)self->prop->data.pointer)[index]));
932                         break;
933                 case IDP_INT:
934                         return PyLong_FromLong( (long)((int*)self->prop->data.pointer)[index] );
935                         break;
936         }
937
938         PyErr_SetString(PyExc_RuntimeError, "invalid/corrupt array type!");
939         return NULL;
940 }
941
942 static int BPy_IDArray_SetItem(BPy_IDArray *self, int index, PyObject *value)
943 {
944         int i;
945         float f;
946         double d;
947
948         if (index < 0 || index >= self->prop->len) {
949                 PyErr_SetString(PyExc_RuntimeError, "index out of range!");
950                 return -1;
951         }
952
953         switch (self->prop->subtype) {
954                 case IDP_FLOAT:
955                         f= (float)PyFloat_AsDouble(value);
956                         if (f==-1 && PyErr_Occurred()) {
957                                 PyErr_SetString(PyExc_TypeError, "expected a float");
958                                 return -1;
959                         }
960                         ((float*)self->prop->data.pointer)[index] = f;
961                         break;
962                 case IDP_DOUBLE:
963                         d= PyFloat_AsDouble(value);
964                         if (d==-1 && PyErr_Occurred()) {
965                                 PyErr_SetString(PyExc_TypeError, "expected a float");
966                                 return -1;
967                         }
968                         ((double*)self->prop->data.pointer)[index] = d;
969                         break;
970                 case IDP_INT:
971                         i= PyLong_AsSsize_t(value);
972                         if (i==-1 && PyErr_Occurred()) {
973                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
974                                 return -1;
975                         }
976
977                         ((int*)self->prop->data.pointer)[index] = i;
978                         break;
979         }
980         return 0;
981 }
982
983 static PySequenceMethods BPy_IDArray_Seq = {
984         (lenfunc) BPy_IDArray_Len,                      /* inquiry sq_length */
985         NULL,                                                           /* binaryfunc sq_concat */
986         NULL,                                                           /* intargfunc sq_repeat */
987         (ssizeargfunc)BPy_IDArray_GetItem,      /* intargfunc sq_item */
988         NULL,                                                           /* intintargfunc sq_slice */
989         (ssizeobjargproc)BPy_IDArray_SetItem,/* intobjargproc sq_ass_item */
990         NULL,                                                           /* intintobjargproc sq_ass_slice */
991         NULL,                                                           /* objobjproc sq_contains */
992                                 /* Added in release 2.0 */
993         NULL,                                                           /* binaryfunc sq_inplace_concat */
994         NULL,                                                           /* intargfunc sq_inplace_repeat */
995 };
996
997 PyTypeObject IDArray_Type = {
998         PyVarObject_HEAD_INIT(NULL, 0)
999         /*  For printing, in format "<module>.<name>" */
1000         "Blender IDArray",           /* char *tp_name; */
1001         sizeof( BPy_IDArray ),       /* int tp_basicsize; */
1002         0,                          /* tp_itemsize;  For allocation */
1003
1004         /* Methods to implement standard operations */
1005
1006         NULL,                                           /* destructor tp_dealloc; */
1007         NULL,                       /* printfunc tp_print; */
1008         NULL,     /* getattrfunc tp_getattr; */
1009         NULL,     /* setattrfunc tp_setattr; */
1010         NULL,                       /* cmpfunc tp_compare; */
1011         ( reprfunc ) IDArray_repr,     /* reprfunc tp_repr; */
1012
1013         /* Method suites for standard classes */
1014
1015         NULL,                       /* PyNumberMethods *tp_as_number; */
1016         &BPy_IDArray_Seq,                       /* PySequenceMethods *tp_as_sequence; */
1017         NULL,                       /* PyMappingMethods *tp_as_mapping; */
1018
1019         /* More standard operations (here for binary compatibility) */
1020
1021         NULL,                       /* hashfunc tp_hash; */
1022         NULL,                       /* ternaryfunc tp_call; */
1023         NULL,                       /* reprfunc tp_str; */
1024         NULL,                       /* getattrofunc tp_getattro; */
1025         NULL,                       /* setattrofunc tp_setattro; */
1026
1027         /* Functions to access object as input/output buffer */
1028         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1029
1030   /*** Flags to define presence of optional/expanded features ***/
1031         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
1032
1033         NULL,                       /*  char *tp_doc;  Documentation string */
1034   /*** Assigned meaning in release 2.0 ***/
1035         /* call function for all accessible objects */
1036         NULL,                       /* traverseproc tp_traverse; */
1037
1038         /* delete references to contained objects */
1039         NULL,                       /* inquiry tp_clear; */
1040
1041   /***  Assigned meaning in release 2.1 ***/
1042   /*** rich comparisons ***/
1043         NULL,                       /* richcmpfunc tp_richcompare; */
1044
1045   /***  weak reference enabler ***/
1046         0,                          /* long tp_weaklistoffset; */
1047
1048   /*** Added in release 2.2 ***/
1049         /*   Iterators */
1050         NULL,                       /* getiterfunc tp_iter; */
1051         NULL,                       /* iternextfunc tp_iternext; */
1052
1053   /*** Attribute descriptor and subclassing stuff ***/
1054         BPy_IDArray_methods,            /* struct PyMethodDef *tp_methods; */
1055         NULL,                       /* struct PyMemberDef *tp_members; */
1056         BPy_IDArray_getseters,       /* struct PyGetSetDef *tp_getset; */
1057         NULL,                       /* struct _typeobject *tp_base; */
1058         NULL,                       /* PyObject *tp_dict; */
1059         NULL,                       /* descrgetfunc tp_descr_get; */
1060         NULL,                       /* descrsetfunc tp_descr_set; */
1061         0,                          /* long tp_dictoffset; */
1062         NULL,                       /* initproc tp_init; */
1063         NULL,                       /* allocfunc tp_alloc; */
1064         NULL,                       /* newfunc tp_new; */
1065         /*  Low-level free-memory routine */
1066         NULL,                       /* freefunc tp_free;  */
1067         /* For PyObject_IS_GC */
1068         NULL,                       /* inquiry tp_is_gc;  */
1069         NULL,                       /* PyObject *tp_bases; */
1070         /* method resolution order */
1071         NULL,                       /* PyObject *tp_mro;  */
1072         NULL,                       /* PyObject *tp_cache; */
1073         NULL,                       /* PyObject *tp_subclasses; */
1074         NULL,                       /* PyObject *tp_weaklist; */
1075         NULL
1076 };
1077
1078 /*********** ID Property Group iterator ********/
1079
1080 static PyObject *IDGroup_Iter_iterself(PyObject *self)
1081 {
1082         Py_XINCREF(self);
1083         return self;
1084 }
1085
1086 static PyObject *IDGroup_Iter_repr(BPy_IDGroup_Iter *self)
1087 {
1088         return PyUnicode_FromFormat("(ID Property Group Iter \"%s\")", self->group->prop->name);
1089 }
1090
1091 static PyObject *BPy_Group_Iter_Next(BPy_IDGroup_Iter *self)
1092 {
1093         IDProperty *cur=NULL;
1094         PyObject *ret;
1095
1096         if (self->cur) {
1097                 cur = self->cur;
1098                 self->cur = self->cur->next;
1099                 if (self->mode == IDPROP_ITER_ITEMS) {
1100                         ret = PyTuple_New(2);
1101                         PyTuple_SET_ITEM(ret, 0, PyUnicode_FromString(cur->name));
1102                         PyTuple_SET_ITEM(ret, 1, BPy_IDGroup_WrapData(self->group->id, cur));
1103                         return ret;
1104                 }
1105                 else {
1106                         return PyUnicode_FromString(cur->name);
1107                 }
1108         }
1109         else {
1110                 PyErr_SetString(PyExc_StopIteration, "iterator at end");
1111                 return NULL;
1112         }
1113 }
1114
1115 PyTypeObject IDGroup_Iter_Type = {
1116         PyVarObject_HEAD_INIT(NULL, 0)
1117         /*  For printing, in format "<module>.<name>" */
1118         "Blender IDGroup_Iter",           /* char *tp_name; */
1119         sizeof( BPy_IDGroup_Iter ),       /* int tp_basicsize; */
1120         0,                          /* tp_itemsize;  For allocation */
1121
1122         /* Methods to implement standard operations */
1123
1124         NULL,                                           /* destructor tp_dealloc; */
1125         NULL,                       /* printfunc tp_print; */
1126         NULL,     /* getattrfunc tp_getattr; */
1127         NULL,     /* setattrfunc tp_setattr; */
1128         NULL,                       /* cmpfunc tp_compare; */
1129         ( reprfunc ) IDGroup_Iter_repr,     /* reprfunc tp_repr; */
1130
1131         /* Method suites for standard classes */
1132
1133         NULL,                       /* PyNumberMethods *tp_as_number; */
1134         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1135         NULL,                       /* PyMappingMethods *tp_as_mapping; */
1136
1137         /* More standard operations (here for binary compatibility) */
1138
1139         NULL,                       /* hashfunc tp_hash; */
1140         NULL,                       /* ternaryfunc tp_call; */
1141         NULL,                       /* reprfunc tp_str; */
1142         NULL,                       /* getattrofunc tp_getattro; */
1143         NULL,                       /* setattrofunc tp_setattro; */
1144
1145         /* Functions to access object as input/output buffer */
1146         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1147
1148   /*** Flags to define presence of optional/expanded features ***/
1149         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
1150
1151         NULL,                       /*  char *tp_doc;  Documentation string */
1152   /*** Assigned meaning in release 2.0 ***/
1153         /* call function for all accessible objects */
1154         NULL,                       /* traverseproc tp_traverse; */
1155
1156         /* delete references to contained objects */
1157         NULL,                       /* inquiry tp_clear; */
1158
1159   /***  Assigned meaning in release 2.1 ***/
1160   /*** rich comparisons ***/
1161         NULL,                       /* richcmpfunc tp_richcompare; */
1162
1163   /***  weak reference enabler ***/
1164         0,                          /* long tp_weaklistoffset; */
1165
1166   /*** Added in release 2.2 ***/
1167         /*   Iterators */
1168         IDGroup_Iter_iterself,              /* getiterfunc tp_iter; */
1169         (iternextfunc) BPy_Group_Iter_Next, /* iternextfunc tp_iternext; */
1170 };
1171
1172 void IDProp_Init_Types(void)
1173 {
1174         PyType_Ready( &IDGroup_Type );
1175         PyType_Ready( &IDGroup_Iter_Type );
1176         PyType_Ready( &IDArray_Type );
1177 }