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