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