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