svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r20849:20855
[blender.git] / source / blender / python / intern / bpy_rna.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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * Contributor(s): Campbell Barton
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 #include "bpy_rna.h"
26 #include "bpy_compat.h"
27 #include "bpy_util.h"
28 //#include "blendef.h"
29 #include "BLI_dynstr.h"
30 #include "BLI_listbase.h"
31 #include "BLI_string.h"
32 #include "float.h" /* FLT_MIN/MAX */
33
34 #include "RNA_access.h"
35 #include "RNA_define.h" /* for defining our own rna */
36
37 #include "MEM_guardedalloc.h"
38 #include "BKE_context.h"
39 #include "BKE_global.h" /* evil G.* */
40 #include "BKE_report.h"
41
42 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
43 {
44         return (a->ptr.data==b->ptr.data) ? 0 : -1;
45 }
46
47 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
48 {
49         return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
50 }
51
52 /* For some reason python3 needs these :/ */
53 static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
54 {
55         int cmp_result= -1; /* assume false */
56         if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
57                 cmp_result= pyrna_struct_compare(a, b);
58         }
59
60         return Py_CmpToRich(op, cmp_result);
61 }
62
63 static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, int op)
64 {
65         int cmp_result= -1; /* assume false */
66         if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
67                 cmp_result= pyrna_prop_compare(a, b);
68         }
69
70         return Py_CmpToRich(op, cmp_result);
71 }
72
73 /*----------------------repr--------------------------------------------*/
74 static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
75 {
76         PropertyRNA *prop;
77         char str[512];
78
79         /* print name if available */
80         prop= RNA_struct_name_property(self->ptr.type);
81         if(prop) {
82                 RNA_property_string_get(&self->ptr, prop, str);
83                 return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), str);
84         }
85
86         return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(self->ptr.type));
87 }
88
89 static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
90 {
91         PropertyRNA *prop;
92         PointerRNA ptr;
93         char str[512];
94
95         /* if a pointer, try to print name of pointer target too */
96         if(RNA_property_type(self->prop) == PROP_POINTER) {
97                 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
98
99                 if(ptr.data) {
100                         prop= RNA_struct_name_property(ptr.type);
101                         if(prop) {
102                                 RNA_property_string_get(&ptr, prop, str);
103                                 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), str);
104                         }
105                 }
106         }
107
108         return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
109 }
110
111 static long pyrna_struct_hash( BPy_StructRNA * self )
112 {
113         return (long)self->ptr.data;
114 }
115
116 /* use our own dealloc so we can free a property if we use one */
117 static void pyrna_struct_dealloc( BPy_StructRNA * self )
118 {
119         /* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
120         if (self->freeptr && self->ptr.data) {
121                 IDP_FreeProperty(self->ptr.data);
122                 MEM_freeN(self->ptr.data);
123                 self->ptr.data= NULL;
124         }
125
126         Py_TYPE(self)->tp_free(self);
127         return;
128 }
129
130 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
131 {
132         const EnumPropertyItem *item;
133         int totitem;
134         
135         RNA_property_enum_items(ptr, prop, &item, &totitem);
136         return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
137 }
138
139 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
140 {
141         PyObject *ret;
142         int type = RNA_property_type(prop);
143         int len = RNA_property_array_length(prop);
144
145         if (len > 0) {
146                 /* resolve the array from a new pytype */
147                 return pyrna_prop_CreatePyObject(ptr, prop);
148         }
149         
150         /* see if we can coorce into a python type - PropertyType */
151         switch (type) {
152         case PROP_BOOLEAN:
153                 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
154                 break;
155         case PROP_INT:
156                 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
157                 break;
158         case PROP_FLOAT:
159                 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
160                 break;
161         case PROP_STRING:
162         {
163                 char *buf;
164                 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
165                 ret = PyUnicode_FromString( buf );
166                 MEM_freeN(buf);
167                 break;
168         }
169         case PROP_ENUM:
170         {
171                 const char *identifier;
172                 int val = RNA_property_enum_get(ptr, prop);
173                 
174                 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
175                         ret = PyUnicode_FromString( identifier );
176                 } else {
177                         PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
178                         ret = NULL;
179                 }
180
181                 break;
182         }
183         case PROP_POINTER:
184         {
185                 PointerRNA newptr;
186                 newptr= RNA_property_pointer_get(ptr, prop);
187                 if (newptr.data) {
188                         ret = pyrna_struct_CreatePyObject(&newptr);
189                 } else {
190                         ret = Py_None;
191                         Py_INCREF(ret);
192                 }
193                 break;
194         }
195         case PROP_COLLECTION:
196                 ret = pyrna_prop_CreatePyObject(ptr, prop);
197                 break;
198         default:
199                 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
200                 ret = NULL;
201                 break;
202         }
203         
204         return ret;
205 }
206
207 /* This function is only used by operators right now
208  * Its used for taking keyword args and filling in property values */
209 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefix)
210 {
211         int error_val = 0;
212         int totkw;
213         const char *arg_name= NULL;
214         PyObject *item;
215
216         PropertyRNA *prop, *iterprop;
217         CollectionPropertyIterator iter;
218
219         iterprop= RNA_struct_iterator_property(ptr->type);
220         RNA_property_collection_begin(ptr, iterprop, &iter);
221
222         totkw = kw ? PyDict_Size(kw):0;
223
224         for(; iter.valid; RNA_property_collection_next(&iter)) {
225                 prop= iter.ptr.data;
226
227                 arg_name= RNA_property_identifier(prop);
228
229                 if (strcmp(arg_name, "rna_type")==0) continue;
230
231                 if (kw==NULL) {
232                         PyErr_Format( PyExc_AttributeError, "%s: no keywords, expected \"%s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
233                         error_val= -1;
234                         break;
235                 }
236
237                 item= PyDict_GetItemString(kw, arg_name);
238
239                 if (item == NULL) {
240                         PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
241                         error_val = -1; /* pyrna_py_to_prop sets the error */
242                         break;
243                 }
244
245                 if (pyrna_py_to_prop(ptr, prop, NULL, item)) {
246                         error_val= -1;
247                         break;
248                 }
249
250                 totkw--;
251         }
252
253         RNA_property_collection_end(&iter);
254
255         if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
256                 PyObject *key, *value;
257                 Py_ssize_t pos = 0;
258
259                 while (PyDict_Next(kw, &pos, &key, &value)) {
260                         arg_name= _PyUnicode_AsString(key);
261                         if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
262                         arg_name= NULL;
263                 }
264
265                 PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
266                 error_val = -1;
267         }
268
269         return error_val;
270 }
271
272 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
273
274 PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
275 {
276         static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
277         PyObject *self= PyTuple_New(2);
278         PyObject *ret;
279         PyTuple_SET_ITEM(self, 0, pyrna_struct_CreatePyObject(ptr));
280         PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
281         
282         ret= PyCFunction_New(&func_meth, self);
283         Py_DECREF(self);
284         
285         return ret;
286 }
287
288
289 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value)
290 {
291         /* XXX hard limits should be checked here */
292         int type = RNA_property_type(prop);
293         int len = RNA_property_array_length(prop);
294         
295         if (len > 0) {
296                 PyObject *item;
297                 int i;
298                 
299                 if (!PySequence_Check(value)) {
300                         PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
301                         return -1;
302                 }
303                 
304                 if ((int)PySequence_Length(value) != len) {
305                         PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
306                         return -1;
307                 }
308                 
309                 /* for arrays we have a limited number of types */
310                 switch (type) {
311                 case PROP_BOOLEAN:
312                 {
313                         int *param_arr;
314                         if(data)        param_arr= (int*)data;
315                         else            param_arr= MEM_mallocN(sizeof(char) * len, "pyrna bool array");
316
317                         
318                         /* collect the variables before assigning, incase one of them is incorrect */
319                         for (i=0; i<len; i++) {
320                                 item = PySequence_GetItem(value, i);
321                                 param_arr[i] = PyObject_IsTrue( item );
322                                 Py_DECREF(item);
323                                 
324                                 if (param_arr[i] < 0) {
325                                         if(data==NULL)
326                                                 MEM_freeN(param_arr);
327                                         PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
328                                         return -1;
329                                 }
330                         }
331                         if(data==NULL) {
332                                 RNA_property_boolean_set_array(ptr, prop, param_arr);
333                                 MEM_freeN(param_arr);
334                         }
335
336                         break;
337                 }
338                 case PROP_INT:
339                 {
340                         int *param_arr;
341                         if(data)        param_arr= (int*)data;
342                         else            param_arr= MEM_mallocN(sizeof(int) * len, "pyrna int array");
343
344                         
345                         /* collect the variables */
346                         for (i=0; i<len; i++) {
347                                 item = PySequence_GetItem(value, i);
348                                 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
349                                 Py_DECREF(item);
350                         }
351                         
352                         if (PyErr_Occurred()) {
353                                 if(data==NULL)
354                                         MEM_freeN(param_arr);
355                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
356                                 return -1;
357                         }
358                         if(data==NULL) {
359                                 RNA_property_int_set_array(ptr, prop, param_arr);
360                                 MEM_freeN(param_arr);
361                         }
362                         break;
363                 }
364                 case PROP_FLOAT:
365                 {
366                         float *param_arr;
367                         if(data)        param_arr = (float*)data;
368                         else            param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
369
370
371                         
372                         /* collect the variables */
373                         for (i=0; i<len; i++) {
374                                 item = PySequence_GetItem(value, i);
375                                 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
376                                 Py_DECREF(item);
377                         }
378                         
379                         if (PyErr_Occurred()) {
380                                 if(data==NULL)
381                                         MEM_freeN(param_arr);
382                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
383                                 return -1;
384                         }
385                         if(data==NULL) {
386                                 RNA_property_float_set_array(ptr, prop, param_arr);                             
387                                 MEM_freeN(param_arr);
388                         }
389                         break;
390                 }
391                 }
392         } else {
393                 /* Normal Property (not an array) */
394                 
395                 /* see if we can coorce into a python type - PropertyType */
396                 switch (type) {
397                 case PROP_BOOLEAN:
398                 {
399                         int param = PyObject_IsTrue( value );
400                         
401                         if( param < 0 ) {
402                                 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
403                                 return -1;
404                         } else {
405                                 if(data)        *((int*)data)= param;
406                                 else            RNA_property_boolean_set(ptr, prop, param);
407                         }
408                         break;
409                 }
410                 case PROP_INT:
411                 {
412                         int param = PyLong_AsSsize_t(value);
413                         if (PyErr_Occurred()) {
414                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
415                                 return -1;
416                         } else {
417                                 if(data)        *((int*)data)= param;
418                                 else            RNA_property_int_set(ptr, prop, param);
419                         }
420                         break;
421                 }
422                 case PROP_FLOAT:
423                 {
424                         float param = PyFloat_AsDouble(value);
425                         if (PyErr_Occurred()) {
426                                 PyErr_SetString(PyExc_TypeError, "expected a float type");
427                                 return -1;
428                         } else {
429                                 if(data)        *((float*)data)= param;
430                                 else            RNA_property_float_set(ptr, prop, param);
431                         }
432                         break;
433                 }
434                 case PROP_STRING:
435                 {
436                         char *param = _PyUnicode_AsString(value);
437                         
438                         if (param==NULL) {
439                                 PyErr_SetString(PyExc_TypeError, "expected a string type");
440                                 return -1;
441                         } else {
442                                 if(data)        *((char**)data)= param;
443                                 else            RNA_property_string_set(ptr, prop, param);
444                         }
445                         break;
446                 }
447                 case PROP_ENUM:
448                 {
449                         char *param = _PyUnicode_AsString(value);
450                         
451                         if (param==NULL) {
452                                 char *enum_str= pyrna_enum_as_string(ptr, prop);
453                                 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
454                                 MEM_freeN(enum_str);
455                                 return -1;
456                         } else {
457                                 int val;
458                                 if (RNA_property_enum_value(ptr, prop, param, &val)) {
459                                         if(data)        *((int*)data)= val;
460                                         else            RNA_property_enum_set(ptr, prop, val);
461                                 } else {
462                                         char *enum_str= pyrna_enum_as_string(ptr, prop);
463                                         PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
464                                         MEM_freeN(enum_str);
465                                         return -1;
466                                 }
467                         }
468                         
469                         break;
470                 }
471                 case PROP_POINTER:
472                 {
473                         StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
474
475                         if(!BPy_StructRNA_Check(value) && value != Py_None) {
476                                 PointerRNA tmp;
477                                 RNA_pointer_create(NULL, ptype, NULL, &tmp);
478                                 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
479                                 return -1;
480                         } else {
481                                 BPy_StructRNA *param= (BPy_StructRNA*)value;
482                                 int raise_error= 0;
483                                 if(data) {
484                                         if(ptype == &RNA_AnyType) {
485                                                 if(value == Py_None)
486                                                         memset(data, 0, sizeof(PointerRNA));
487                                                 else
488                                                         *((PointerRNA*)data)= param->ptr;
489                                         }
490                                         else if(value == Py_None) {
491                                                 *((void**)data)= NULL;
492                                         }
493                                         else if(RNA_struct_is_a(param->ptr.type, ptype)) {
494                                                 *((void**)data)= param->ptr.data;
495                                         }
496                                         else {
497                                                 raise_error= 1;
498                                         }
499                                 }
500                                 else {
501                                         /* data==NULL, assign to RNA */
502                                         if(value == Py_None) {
503                                                 PointerRNA valueptr;
504                                                 memset(&valueptr, 0, sizeof(valueptr));
505                                                 RNA_property_pointer_set(ptr, prop, valueptr);
506                                         }
507                                         else if(RNA_struct_is_a(param->ptr.type, ptype)) {
508                                                 RNA_property_pointer_set(ptr, prop, param->ptr);
509                                         }
510                                         else {
511                                                 PointerRNA tmp;
512                                                 RNA_pointer_create(NULL, ptype, NULL, &tmp);
513                                                 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
514                                                 return -1;
515                                         }
516                                 }
517                                 
518                                 if(raise_error) {
519                                         PointerRNA tmp;
520                                         RNA_pointer_create(NULL, ptype, NULL, &tmp);
521                                         PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
522                                         return -1;
523                                 }
524                         }
525                         break;
526                 }
527                 case PROP_COLLECTION:
528                 {
529                         int seq_len, i;
530                         PyObject *item;
531                         PointerRNA itemptr;
532                         
533                         /* convert a sequence of dict's into a collection */
534                         if(!PySequence_Check(value)) {
535                                 PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
536                                 return -1;
537                         }
538                         
539                         seq_len = PySequence_Length(value);
540                         for(i=0; i<seq_len; i++) {
541                                 item= PySequence_GetItem(value, i);
542                                 if(item==NULL || PyDict_Check(item)==0) {
543                                         PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
544                                         Py_XDECREF(item);
545                                         return -1;
546                                 }
547                                 
548                                 RNA_property_collection_add(ptr, prop, &itemptr);
549                                 if(pyrna_pydict_to_props(&itemptr, item, "Converting a python list to an RNA collection")==-1) {
550                                         Py_DECREF(item);
551                                         return -1;
552                                 }
553                                 Py_DECREF(item);
554                         }
555                         
556                         break;
557                 }
558                 default:
559                         PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_prop)");
560                         return -1;
561                         break;
562                 }
563         }
564         
565         return 0;
566 }
567
568 static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
569 {
570         PyObject *ret;
571         int type = RNA_property_type(prop);
572         
573         /* see if we can coorce into a python type - PropertyType */
574         switch (type) {
575         case PROP_BOOLEAN:
576                 ret = PyBool_FromLong( RNA_property_boolean_get_index(ptr, prop, index) );
577                 break;
578         case PROP_INT:
579                 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get_index(ptr, prop, index) );
580                 break;
581         case PROP_FLOAT:
582                 ret = PyFloat_FromDouble( RNA_property_float_get_index(ptr, prop, index) );
583                 break;
584         default:
585                 PyErr_SetString(PyExc_AttributeError, "not an array type");
586                 ret = NULL;
587                 break;
588         }
589         
590         return ret;
591 }
592
593 static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
594 {
595         int ret = 0;
596         int type = RNA_property_type(prop);
597         
598         /* see if we can coorce into a python type - PropertyType */
599         switch (type) {
600         case PROP_BOOLEAN:
601         {
602                 int param = PyObject_IsTrue( value );
603                 
604                 if( param < 0 ) {
605                         PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
606                         ret = -1;
607                 } else {
608                         RNA_property_boolean_set_index(ptr, prop, index, param);
609                 }
610                 break;
611         }
612         case PROP_INT:
613         {
614                 int param = PyLong_AsSsize_t(value);
615                 if (PyErr_Occurred()) {
616                         PyErr_SetString(PyExc_TypeError, "expected an int type");
617                         ret = -1;
618                 } else {
619                         RNA_property_int_set_index(ptr, prop, index, param);
620                 }
621                 break;
622         }
623         case PROP_FLOAT:
624         {
625                 float param = PyFloat_AsDouble(value);
626                 if (PyErr_Occurred()) {
627                         PyErr_SetString(PyExc_TypeError, "expected a float type");
628                         ret = -1;
629                 } else {
630                         RNA_property_float_set_index(ptr, prop, index, param);
631                 }
632                 break;
633         }
634         default:
635                 PyErr_SetString(PyExc_AttributeError, "not an array type");
636                 ret = -1;
637                 break;
638         }
639         
640         return ret;
641 }
642
643 //---------------sequence-------------------------------------------
644 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
645 {
646         Py_ssize_t len;
647         
648         if (RNA_property_type(self->prop) == PROP_COLLECTION) {
649                 len = RNA_property_collection_length(&self->ptr, self->prop);
650         } else {
651                 len = RNA_property_array_length(self->prop);
652                 
653                 if (len==0) { /* not an array*/
654                         PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
655                         return -1;
656                 }
657         }
658         
659         return len;
660 }
661
662 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
663 {
664         PyObject *ret;
665         PointerRNA newptr;
666         int keynum = 0;
667         char *keyname = NULL;
668         
669         if (PyUnicode_Check(key)) {
670                 keyname = _PyUnicode_AsString(key);
671         } else if (PyLong_Check(key)) {
672                 keynum = PyLong_AsSsize_t(key);
673         } else {
674                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
675                 return NULL;
676         }
677         
678         if (RNA_property_type(self->prop) == PROP_COLLECTION) {
679                 int ok;
680                 if (keyname)    ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
681                 else                    ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
682                 
683                 if (ok) {
684                         ret = pyrna_struct_CreatePyObject(&newptr);
685                 } else {
686                         PyErr_SetString(PyExc_AttributeError, "out of range");
687                         ret = NULL;
688                 }
689                 
690         } else if (keyname) {
691                 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
692                 ret = NULL;
693         } else {
694                 int len = RNA_property_array_length(self->prop);
695                 
696                 if (len==0) { /* not an array*/
697                         PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
698                         ret = NULL;
699                 }
700                 
701                 if (keynum >= len){
702                         PyErr_SetString(PyExc_AttributeError, "index out of range");
703                         ret = NULL;
704                 } else { /* not an array*/
705                         ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
706                 }
707         }
708         
709         return ret;
710 }
711
712
713 static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
714 {
715         int ret = 0;
716         int keynum = 0;
717         char *keyname = NULL;
718         
719         if (!RNA_property_editable(&self->ptr, self->prop)) {
720                 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
721                 return -1;
722         }
723         
724         if (PyUnicode_Check(key)) {
725                 keyname = _PyUnicode_AsString(key);
726         } else if (PyLong_Check(key)) {
727                 keynum = PyLong_AsSsize_t(key);
728         } else {
729                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - invalid key, key must be a string or an int");
730                 return -1;
731         }
732         
733         if (RNA_property_type(self->prop) == PROP_COLLECTION) {
734                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - assignment is not supported for collections (yet)");
735                 ret = -1;
736         } else if (keyname) {
737                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - string keys are only supported for collections");
738                 ret = -1;
739         } else {
740                 int len = RNA_property_array_length(self->prop);
741                 
742                 if (len==0) { /* not an array*/
743                         PyErr_Format(PyExc_AttributeError, "PropertyRNA - not an array or collection %d", keynum);
744                         ret = -1;
745                 }
746                 
747                 if (keynum >= len){
748                         PyErr_SetString(PyExc_AttributeError, "PropertyRNA - index out of range");
749                         ret = -1;
750                 } else {
751                         ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
752                 }
753         }
754         
755         return ret;
756 }
757
758
759
760 static PyMappingMethods pyrna_prop_as_mapping = {
761         ( lenfunc ) pyrna_prop_len,     /* mp_length */
762         ( binaryfunc ) pyrna_prop_subscript,    /* mp_subscript */
763         ( objobjargproc ) pyrna_prop_assign_subscript,  /* mp_ass_subscript */
764 };
765
766 static int pyrna_prop_contains(BPy_PropertyRNA * self, PyObject *value)
767 {
768         PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
769         char *keyname = _PyUnicode_AsString(value);
770         
771         if(keyname==NULL) {
772                 PyErr_SetString(PyExc_SystemError, "PropertyRNA - key in prop, key must be a string type");
773                 return -1;
774         }
775         
776         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
777                 PyErr_SetString(PyExc_SystemError, "PropertyRNA - key in prop, is only valid for collection types");
778                 return -1;
779         }
780         
781         
782         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
783                 return 1;
784         
785         return 0;
786 }
787
788 static PySequenceMethods pyrna_prop_as_sequence = {
789         NULL,           /* Cant set the len otherwise it can evaluate as false */
790         NULL,           /* sq_concat */
791         NULL,           /* sq_repeat */
792         NULL,           /* sq_item */
793         NULL,           /* sq_slice */
794         NULL,           /* sq_ass_item */
795         NULL,           /* sq_ass_slice */
796         (objobjproc)pyrna_prop_contains,        /* sq_contains */
797 };
798
799 static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
800 {
801         PyObject *ret, *dict;
802         PyObject *pystring;
803         
804         /* for looping over attrs and funcs */
805         CollectionPropertyIterator iter;
806         PropertyRNA *iterprop;
807         
808         /* Include this incase this instance is a subtype of a python class
809          * In these instances we may want to return a function or variable provided by the subtype
810          * */
811
812         if (BPy_StructRNA_CheckExact(self)) {
813                 ret = PyList_New(0);
814         } else {
815                 pystring = PyUnicode_FromString("__dict__");
816                 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
817                 Py_DECREF(pystring);
818
819                 if (dict==NULL) {
820                         PyErr_Clear();
821                         ret = PyList_New(0);
822                 }
823                 else {
824                         ret = PyDict_Keys(dict);
825                         Py_DECREF(dict);
826                 }
827         }
828         
829         /* Collect RNA items*/
830         {
831                 /*
832                  * Collect RNA attributes
833                  */
834                 PropertyRNA *nameprop;
835                 char name[256], *nameptr;
836
837                 iterprop= RNA_struct_iterator_property(self->ptr.type);
838                 RNA_property_collection_begin(&self->ptr, iterprop, &iter);
839
840                 for(; iter.valid; RNA_property_collection_next(&iter)) {
841                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
842                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
843                                 
844                                 pystring = PyUnicode_FromString(nameptr);
845                                 PyList_Append(ret, pystring);
846                                 Py_DECREF(pystring);
847                                 
848                                 if ((char *)&name != nameptr)
849                                         MEM_freeN(nameptr);
850                         }
851                 }
852                 RNA_property_collection_end(&iter);
853         
854         }
855         
856         
857         {
858                 /*
859                  * Collect RNA function items
860                  */
861                 PointerRNA tptr;
862
863                 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
864                 iterprop= RNA_struct_find_property(&tptr, "functions");
865
866                 RNA_property_collection_begin(&tptr, iterprop, &iter);
867
868                 for(; iter.valid; RNA_property_collection_next(&iter)) {
869                         pystring = PyUnicode_FromString(RNA_function_identifier(iter.ptr.data));
870                         PyList_Append(ret, pystring);
871                         Py_DECREF(pystring);
872                 }
873
874                 RNA_property_collection_end(&iter);
875         }
876         
877         return ret;
878 }
879
880
881 //---------------getattr--------------------------------------------
882 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
883 {
884         char *name = _PyUnicode_AsString(pyname);
885         PyObject *ret;
886         PropertyRNA *prop;
887         FunctionRNA *func;
888         
889         /* Include this incase this instance is a subtype of a python class
890          * In these instances we may want to return a function or variable provided by the subtype
891          * 
892          * Also needed to return methods when its not a subtype
893          * */
894         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
895         if (ret)        return ret;
896         else            PyErr_Clear();
897         /* done with subtypes */
898         
899         if ((prop = RNA_struct_find_property(&self->ptr, name))) {
900                 ret = pyrna_prop_to_py(&self->ptr, prop);
901         }
902         else if ((func = RNA_struct_find_function(&self->ptr, name))) {
903                 ret = pyrna_func_to_py(&self->ptr, func);
904         }
905         else if (self->ptr.type == &RNA_Context) {
906                 PointerRNA newptr;
907                 ListBase newlb;
908
909                 CTX_data_get(self->ptr.data, name, &newptr, &newlb);
910
911         if (newptr.data) {
912             ret = pyrna_struct_CreatePyObject(&newptr);
913                 }
914                 else if (newlb.first) {
915                         CollectionPointerLink *link;
916                         PyObject *linkptr;
917
918                         ret = PyList_New(0);
919
920                         for(link=newlb.first; link; link=link->next) {
921                                 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
922                                 PyList_Append(ret, linkptr);
923                                 Py_DECREF(linkptr);
924                         }
925                 }
926         else {
927             ret = Py_None;
928             Py_INCREF(ret);
929         }
930
931                 BLI_freelistN(&newlb);
932         }
933         else {
934                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
935                 ret = NULL;
936         }
937         
938         return ret;
939 }
940
941 //--------------- setattr-------------------------------------------
942 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
943 {
944         char *name = _PyUnicode_AsString(pyname);
945         PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
946         
947         if (prop==NULL) {
948                 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
949                         return 0;
950                 }
951                 else {
952                         PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
953                         return -1;
954                 }
955         }               
956         
957         if (!RNA_property_editable(&self->ptr, prop)) {
958                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
959                 return -1;
960         }
961                 
962         /* pyrna_py_to_prop sets its own exceptions */
963         return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
964 }
965
966 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
967 {
968         PyObject *ret;
969         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
970                 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
971                 ret = NULL;
972         } else {
973                 PyObject *item;
974                 CollectionPropertyIterator iter;
975                 PropertyRNA *nameprop;
976                 char name[256], *nameptr;
977
978                 ret = PyList_New(0);
979                 
980                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
981                 for(; iter.valid; RNA_property_collection_next(&iter)) {
982                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
983                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));                                
984                                 
985                                 /* add to python list */
986                                 item = PyUnicode_FromString( nameptr );
987                                 PyList_Append(ret, item);
988                                 Py_DECREF(item);
989                                 /* done */
990                                 
991                                 if ((char *)&name != nameptr)
992                                         MEM_freeN(nameptr);
993                         }
994                 }
995                 RNA_property_collection_end(&iter);
996         }
997         
998         return ret;
999 }
1000
1001 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1002 {
1003         PyObject *ret;
1004         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1005                 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1006                 ret = NULL;
1007         } else {
1008                 PyObject *item;
1009                 CollectionPropertyIterator iter;
1010                 PropertyRNA *nameprop;
1011                 char name[256], *nameptr;
1012
1013                 ret = PyList_New(0);
1014                 
1015                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1016                 for(; iter.valid; RNA_property_collection_next(&iter)) {
1017                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
1018                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
1019                                 
1020                                 /* add to python list */
1021                                 item = Py_BuildValue("(NN)", PyUnicode_FromString( nameptr ), pyrna_struct_CreatePyObject(&iter.ptr));
1022                                 PyList_Append(ret, item);
1023                                 Py_DECREF(item);
1024                                 /* done */
1025                                 
1026                                 if ((char *)&name != nameptr)
1027                                         MEM_freeN(nameptr);
1028                         }
1029                 }
1030                 RNA_property_collection_end(&iter);
1031         }
1032         
1033         return ret;
1034 }
1035
1036
1037 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1038 {
1039         PyObject *ret;
1040         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1041                 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1042                 ret = NULL;
1043         } else {
1044                 PyObject *item;
1045                 CollectionPropertyIterator iter;
1046                 PropertyRNA *nameprop;
1047                 
1048                 ret = PyList_New(0);
1049                 
1050                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1051                 for(; iter.valid; RNA_property_collection_next(&iter)) {
1052                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
1053                                 item = pyrna_struct_CreatePyObject(&iter.ptr);
1054                                 PyList_Append(ret, item);
1055                                 Py_DECREF(item);
1056                         }
1057                 }
1058                 RNA_property_collection_end(&iter);
1059         }
1060         
1061         return ret;
1062 }
1063
1064 /* A bit of a kludge, make a list out of a collection or array,
1065  * then return the lists iter function, not especially fast but convenient for now */
1066 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
1067 {
1068         /* Try get values from a collection */
1069         PyObject *ret = pyrna_prop_values(self);
1070         
1071         if (ret==NULL) {
1072                 /* collection did not work, try array */
1073                 int len = RNA_property_array_length(self->prop);
1074                 
1075                 if (len) {
1076                         int i;
1077                         PyErr_Clear();
1078                         ret = PyList_New(len);
1079                         
1080                         for (i=0; i < len; i++) {
1081                                 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
1082                         }
1083                 }
1084         }
1085         
1086         if (ret) {
1087                 /* we know this is a list so no need to PyIter_Check */
1088                 PyObject *iter = PyObject_GetIter(ret); 
1089                 Py_DECREF(ret);
1090                 return iter;
1091         }
1092         
1093         PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
1094         return NULL;
1095 }
1096
1097 static struct PyMethodDef pyrna_struct_methods[] = {
1098         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
1099         {NULL, NULL, 0, NULL}
1100 };
1101
1102 static struct PyMethodDef pyrna_prop_methods[] = {
1103         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
1104         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
1105         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
1106         {NULL, NULL, 0, NULL}
1107 };
1108
1109 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1110  * todo - also accept useful args */
1111 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1112
1113         BPy_StructRNA *base = NULL;
1114         
1115         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
1116                 return NULL;
1117         
1118         if (type == &pyrna_struct_Type) {
1119                 return pyrna_struct_CreatePyObject(&base->ptr);
1120         } else {
1121                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
1122                 ret->ptr = base->ptr;
1123                 return (PyObject *)ret;
1124         }
1125 }
1126
1127 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1128  * todo - also accept useful args */
1129 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1130
1131         BPy_PropertyRNA *base = NULL;
1132         
1133         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
1134                 return NULL;
1135         
1136         if (type == &pyrna_prop_Type) {
1137                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1138         } else {
1139                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1140                 ret->ptr = base->ptr;
1141                 ret->prop = base->prop;
1142                 return (PyObject *)ret;
1143         }
1144 }
1145
1146 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1147 {
1148         PyObject *ret;
1149         int type = RNA_property_type(prop);
1150         int len = RNA_property_array_length(prop);
1151
1152         int a;
1153
1154         if(len > 0) {
1155                 /* resolve the array from a new pytype */
1156                 ret = PyTuple_New(len);
1157
1158                 switch (type) {
1159                 case PROP_BOOLEAN:
1160                         for(a=0; a<len; a++)
1161                                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1162                         break;
1163                 case PROP_INT:
1164                         for(a=0; a<len; a++)
1165                                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1166                         break;
1167                 case PROP_FLOAT:
1168                         for(a=0; a<len; a++)
1169                                 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1170                         break;
1171                 default:
1172                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1173                         ret = NULL;
1174                         break;
1175                 }
1176         }
1177         else {
1178                 /* see if we can coorce into a python type - PropertyType */
1179                 switch (type) {
1180                 case PROP_BOOLEAN:
1181                         ret = PyBool_FromLong( *(int*)data );
1182                         break;
1183                 case PROP_INT:
1184                         ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1185                         break;
1186                 case PROP_FLOAT:
1187                         ret = PyFloat_FromDouble( *(float*)data );
1188                         break;
1189                 case PROP_STRING:
1190                 {
1191                         ret = PyUnicode_FromString( *(char**)data );
1192                         break;
1193                 }
1194                 case PROP_ENUM:
1195                 {
1196                         const char *identifier;
1197                         int val = *(int*)data;
1198                         
1199                         if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1200                                 ret = PyUnicode_FromString( identifier );
1201                         } else {
1202                                 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1203                                 ret = NULL;
1204                         }
1205
1206                         break;
1207                 }
1208                 case PROP_POINTER:
1209                 {
1210                         PointerRNA newptr;
1211                         StructRNA *type= RNA_property_pointer_type(ptr, prop);
1212
1213                         if(type == &RNA_AnyType) {
1214                                 /* in this case we get the full ptr */
1215                                 newptr= *(PointerRNA*)data;
1216                         }
1217                         else {
1218                                 /* XXX this is missing the ID part! */
1219                                 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1220                         }
1221
1222                         if (newptr.data) {
1223                                 ret = pyrna_struct_CreatePyObject(&newptr);
1224                         } else {
1225                                 ret = Py_None;
1226                                 Py_INCREF(ret);
1227                         }
1228                         break;
1229                 }
1230                 case PROP_COLLECTION:
1231                         /* XXX not supported yet
1232                          * ret = pyrna_prop_CreatePyObject(ptr, prop); */
1233                         ret = NULL;
1234                         break;
1235                 default:
1236                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1237                         ret = NULL;
1238                         break;
1239                 }
1240         }
1241
1242         return ret;
1243 }
1244
1245 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1246 {
1247         PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1248         FunctionRNA *self_func=  PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1249
1250         PointerRNA funcptr;
1251         ParameterList *parms;
1252         ParameterIterator iter;
1253         PropertyRNA *pret, *parm;
1254         PyObject *ret, *item;
1255         int i, tlen, flag, err= 0;
1256         const char *tid, *fid, *pid;
1257         void *retdata= NULL;
1258
1259         /* setup */
1260         RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1261
1262         pret= RNA_function_return(self_func);
1263         tlen= PyTuple_GET_SIZE(args);
1264
1265         parms= RNA_parameter_list_create(self_ptr, self_func);
1266         RNA_parameter_list_begin(parms, &iter);
1267
1268         /* parse function parameters */
1269         for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1270                 parm= iter.parm;
1271
1272                 if (parm==pret) {
1273                         retdata= iter.data;
1274                         continue;
1275                 }
1276
1277                 pid= RNA_property_identifier(parm);
1278                 flag= RNA_property_flag(parm);
1279                 item= NULL;
1280
1281                 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1282                         item= PyTuple_GET_ITEM(args, i);
1283                         i++;
1284                 }
1285                 else if (kw != NULL)
1286                         item= PyDict_GetItemString(kw, pid);  /* borrow ref */
1287
1288                 if (item==NULL) {
1289                         if(flag & PROP_REQUIRED) {
1290                                 tid= RNA_struct_identifier(self_ptr->type);
1291                                 fid= RNA_function_identifier(self_func);
1292
1293                                 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1294                                 err= -1;
1295                                 break;
1296                         }
1297                         else
1298                                 continue;
1299                 }
1300
1301                 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1302
1303                 if(err!=0)
1304                         break;
1305         }
1306
1307         ret= NULL;
1308         if (err==0) {
1309                 /* call function */
1310                 RNA_function_call(self_ptr, self_func, parms);
1311
1312                 /* return value */
1313                 if(pret)
1314                         ret= pyrna_param_to_py(&funcptr, pret, retdata);
1315         }
1316
1317         /* cleanup */
1318         RNA_parameter_list_end(&iter);
1319         RNA_parameter_list_free(parms);
1320
1321         if (ret)
1322                 return ret;
1323
1324         if (err==-1)
1325                 return NULL;
1326
1327         Py_RETURN_NONE;
1328 }
1329
1330 /*-----------------------BPy_StructRNA method def------------------------------*/
1331 PyTypeObject pyrna_struct_Type = {
1332 #if (PY_VERSION_HEX >= 0x02060000)
1333         PyVarObject_HEAD_INIT(NULL, 0)
1334 #else
1335         /* python 2.5 and below */
1336         PyObject_HEAD_INIT( NULL )  /* required py macro */
1337         0,                          /* ob_size */
1338 #endif
1339         "StructRNA",                    /* tp_name */
1340         sizeof( BPy_StructRNA ),        /* tp_basicsize */
1341         0,                      /* tp_itemsize */
1342         /* methods */
1343         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1344         NULL,                       /* printfunc tp_print; */
1345         NULL,                                           /* getattrfunc tp_getattr; */
1346         NULL,                                           /* setattrfunc tp_setattr; */
1347         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1348         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1349
1350         /* Method suites for standard classes */
1351
1352         NULL,                       /* PyNumberMethods *tp_as_number; */
1353         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1354         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
1355
1356         /* More standard operations (here for binary compatibility) */
1357
1358         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
1359         NULL,                                           /* ternaryfunc tp_call; */
1360         NULL,                       /* reprfunc tp_str; */
1361         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1362         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1363
1364         /* Functions to access object as input/output buffer */
1365         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1366
1367   /*** Flags to define presence of optional/expanded features ***/
1368         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1369
1370         NULL,                                           /*  char *tp_doc;  Documentation string */
1371   /*** Assigned meaning in release 2.0 ***/
1372         /* call function for all accessible objects */
1373         NULL,                       /* traverseproc tp_traverse; */
1374
1375         /* delete references to contained objects */
1376         NULL,                       /* inquiry tp_clear; */
1377
1378   /***  Assigned meaning in release 2.1 ***/
1379   /*** rich comparisons ***/
1380         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
1381
1382   /***  weak reference enabler ***/
1383         0,                          /* long tp_weaklistoffset; */
1384
1385   /*** Added in release 2.2 ***/
1386         /*   Iterators */
1387         NULL,                       /* getiterfunc tp_iter; */
1388         NULL,                       /* iternextfunc tp_iternext; */
1389
1390   /*** Attribute descriptor and subclassing stuff ***/
1391         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
1392         NULL,                       /* struct PyMemberDef *tp_members; */
1393         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1394         NULL,                       /* struct _typeobject *tp_base; */
1395         NULL,                       /* PyObject *tp_dict; */
1396         NULL,                       /* descrgetfunc tp_descr_get; */
1397         NULL,                       /* descrsetfunc tp_descr_set; */
1398         0,                          /* long tp_dictoffset; */
1399         NULL,                       /* initproc tp_init; */
1400         NULL,                       /* allocfunc tp_alloc; */
1401         pyrna_struct_new,                       /* newfunc tp_new; */
1402         /*  Low-level free-memory routine */
1403         NULL,                       /* freefunc tp_free;  */
1404         /* For PyObject_IS_GC */
1405         NULL,                       /* inquiry tp_is_gc;  */
1406         NULL,                       /* PyObject *tp_bases; */
1407         /* method resolution order */
1408         NULL,                       /* PyObject *tp_mro;  */
1409         NULL,                       /* PyObject *tp_cache; */
1410         NULL,                       /* PyObject *tp_subclasses; */
1411         NULL,                       /* PyObject *tp_weaklist; */
1412         NULL
1413 };
1414
1415 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1416 PyTypeObject pyrna_prop_Type = {
1417 #if (PY_VERSION_HEX >= 0x02060000)
1418         PyVarObject_HEAD_INIT(NULL, 0)
1419 #else
1420         /* python 2.5 and below */
1421         PyObject_HEAD_INIT( NULL )  /* required py macro */
1422         0,                          /* ob_size */
1423 #endif
1424         
1425         "PropertyRNA",          /* tp_name */
1426         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
1427         0,                      /* tp_itemsize */
1428         /* methods */
1429         NULL,                                           /* tp_dealloc */
1430         NULL,                       /* printfunc tp_print; */
1431         NULL,                                           /* getattrfunc tp_getattr; */
1432         NULL,                       /* setattrfunc tp_setattr; */
1433         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1434         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
1435
1436         /* Method suites for standard classes */
1437
1438         NULL,                       /* PyNumberMethods *tp_as_number; */
1439         &pyrna_prop_as_sequence,        /* PySequenceMethods *tp_as_sequence; */
1440         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
1441
1442         /* More standard operations (here for binary compatibility) */
1443
1444         NULL,                                           /* hashfunc tp_hash; */
1445         NULL,                       /* ternaryfunc tp_call; */
1446         NULL,                       /* reprfunc tp_str; */
1447         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1448         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
1449
1450         /* Functions to access object as input/output buffer */
1451         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1452
1453   /*** Flags to define presence of optional/expanded features ***/
1454         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1455
1456         NULL,                                           /*  char *tp_doc;  Documentation string */
1457   /*** Assigned meaning in release 2.0 ***/
1458         /* call function for all accessible objects */
1459         NULL,                       /* traverseproc tp_traverse; */
1460
1461         /* delete references to contained objects */
1462         NULL,                       /* inquiry tp_clear; */
1463
1464   /***  Assigned meaning in release 2.1 ***/
1465   /*** rich comparisons ***/
1466         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
1467
1468   /***  weak reference enabler ***/
1469         0,                          /* long tp_weaklistoffset; */
1470
1471   /*** Added in release 2.2 ***/
1472         /*   Iterators */
1473         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
1474         NULL,                       /* iternextfunc tp_iternext; */
1475
1476   /*** Attribute descriptor and subclassing stuff ***/
1477         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
1478         NULL,                       /* struct PyMemberDef *tp_members; */
1479         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1480         NULL,                       /* struct _typeobject *tp_base; */
1481         NULL,                       /* PyObject *tp_dict; */
1482         NULL,                       /* descrgetfunc tp_descr_get; */
1483         NULL,                       /* descrsetfunc tp_descr_set; */
1484         0,                          /* long tp_dictoffset; */
1485         NULL,                       /* initproc tp_init; */
1486         NULL,                       /* allocfunc tp_alloc; */
1487         pyrna_prop_new,                         /* newfunc tp_new; */
1488         /*  Low-level free-memory routine */
1489         NULL,                       /* freefunc tp_free;  */
1490         /* For PyObject_IS_GC */
1491         NULL,                       /* inquiry tp_is_gc;  */
1492         NULL,                       /* PyObject *tp_bases; */
1493         /* method resolution order */
1494         NULL,                       /* PyObject *tp_mro;  */
1495         NULL,                       /* PyObject *tp_cache; */
1496         NULL,                       /* PyObject *tp_subclasses; */
1497         NULL,                       /* PyObject *tp_weaklist; */
1498         NULL
1499 };
1500
1501 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1502 {
1503         PointerRNA ptr;
1504         PyObject *item;
1505         
1506         Py_INCREF(newclass);
1507         
1508         if (RNA_struct_py_type_get(srna))
1509                 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
1510         
1511         Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
1512         
1513         RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1514
1515         /* Not 100% needed but useful,
1516          * having an instance within a type looks wrong however this instance IS an rna type */
1517         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1518         item = pyrna_struct_CreatePyObject(&ptr);
1519         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1520         Py_DECREF(item);
1521         /* done with rna instance */
1522 }
1523
1524 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1525 {
1526         PyObject *newclass = NULL;
1527         PropertyRNA *nameprop;
1528
1529         if (ptr->type==NULL) {
1530                 newclass= NULL; /* Nothing to do */
1531         } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1532                 Py_INCREF(newclass);
1533         } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1534                 /* for now, return the base RNA type rather then a real module */
1535                 
1536                 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1537                 
1538                 /* subclass equivelents
1539                 - class myClass(myBase):
1540                         some='value' # or ...
1541                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1542                 */
1543                 char name[256], *nameptr;
1544                 const char *descr= RNA_struct_ui_description(ptr->type);
1545
1546                 PyObject *args = PyTuple_New(3);
1547                 PyObject *bases = PyTuple_New(1);
1548                 PyObject *dict = PyDict_New();
1549                 PyObject *item;
1550                 
1551                 
1552                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1553                 
1554                 // arg 1
1555                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1556                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1557                 
1558                 // arg 2
1559                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1560                 Py_INCREF(&pyrna_struct_Type);
1561
1562                 PyTuple_SET_ITEM(args, 1, bases);
1563                 
1564                 // arg 3 - add an instance of the rna 
1565                 if(descr) {
1566                         item= PyUnicode_FromString(descr);
1567                         PyDict_SetItemString(dict, "__doc__", item);
1568                         Py_DECREF(item);
1569                 }
1570                 
1571                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1572                 
1573                 if (PyErr_Occurred()) {
1574                         PyErr_Print();
1575                         PyErr_Clear();
1576                 }
1577                 
1578                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1579                 Py_DECREF(args);
1580
1581                 if (newclass)
1582                         pyrna_subtype_set_rna(newclass, ptr->data);
1583                 
1584                 if (name != nameptr)
1585                         MEM_freeN(nameptr);
1586         }
1587         
1588         return newclass;
1589 }
1590
1591 /*-----------------------CreatePyObject---------------------------------*/
1592 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1593 {
1594         BPy_StructRNA *pyrna= NULL;
1595         
1596         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1597                 Py_RETURN_NONE;
1598         }
1599         
1600         if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1601                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1602                 
1603                 if (tp) {
1604                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1605                 }
1606                 else {
1607                         fprintf(stderr, "Could not make type\n");
1608                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1609                 }
1610         }
1611         else {
1612                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1613         }
1614         
1615         if( !pyrna ) {
1616                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1617                 return NULL;
1618         }
1619         
1620         pyrna->ptr= *ptr;
1621         pyrna->freeptr= 0;
1622         return ( PyObject * ) pyrna;
1623 }
1624
1625 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1626 {
1627         BPy_PropertyRNA *pyrna;
1628
1629         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1630
1631         if( !pyrna ) {
1632                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1633                 return NULL;
1634         }
1635         
1636         pyrna->ptr = *ptr;
1637         pyrna->prop = prop;
1638                 
1639         return ( PyObject * ) pyrna;
1640 }
1641
1642 PyObject *BPY_rna_module( void )
1643 {
1644         PointerRNA ptr;
1645         
1646         /* This can't be set in the pytype struct because some compilers complain */
1647         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
1648         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
1649         
1650         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1651                 return NULL;
1652         
1653         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1654                 return NULL;
1655
1656         /* for now, return the base RNA type rather then a real module */
1657         RNA_main_pointer_create(G.main, &ptr);
1658         
1659         return pyrna_struct_CreatePyObject(&ptr);
1660 }
1661
1662 #if 0
1663 /* This is a way we can access docstrings for RNA types
1664  * without having the datatypes in blender */
1665 PyObject *BPY_rna_doc( void )
1666 {
1667         PointerRNA ptr;
1668         
1669         /* for now, return the base RNA type rather then a real module */
1670         RNA_blender_rna_pointer_create(&ptr);
1671         
1672         return pyrna_struct_CreatePyObject(&ptr);
1673 }
1674 #endif
1675
1676
1677 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1678  * the self->ptr and self->prop are always set to the "structs" collection */
1679 //---------------getattr--------------------------------------------
1680 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1681 {
1682         PointerRNA newptr;
1683         PyObject *ret;
1684         
1685         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1686         if (ret)        return ret;
1687         else            PyErr_Clear();
1688         
1689         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1690                 ret= pyrna_struct_Subtype(&newptr);
1691                 if (ret==NULL) {
1692                         PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
1693                 }
1694                 return ret;
1695         }
1696         else { /* Override the error */
1697                 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1698                 return NULL;
1699         }
1700 }
1701
1702 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1703 static struct PyMethodDef pyrna_basetype_methods[] = {
1704         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1705         {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
1706         {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
1707         {NULL, NULL, 0, NULL}
1708 };
1709
1710 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1711 {
1712         PyObject *list, *name;
1713         PyMethodDef *meth;
1714         
1715         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1716
1717         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1718                 name = PyUnicode_FromString(meth->ml_name);
1719                 PyList_Append(list, name);
1720                 Py_DECREF(name);
1721         }
1722         
1723         return list;
1724 }
1725
1726 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
1727
1728 PyObject *BPY_rna_types(void)
1729 {
1730         BPy_BaseTypeRNA *self;
1731
1732         if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0)  {
1733                 pyrna_basetype_Type.tp_name = "RNA_Types";
1734                 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1735                 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1736                 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1737                 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1738                 
1739                 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1740                         return NULL;
1741         }
1742         
1743         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1744         
1745         /* avoid doing this lookup for every getattr */
1746         RNA_blender_rna_pointer_create(&self->ptr);
1747         self->prop = RNA_struct_find_property(&self->ptr, "structs");
1748         
1749         return (PyObject *)self;
1750 }
1751
1752
1753
1754 /* Orphan functions, not sure where they should go */
1755
1756 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1757  * This isnt incorrect since its a python object - but be careful */
1758 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1759 {
1760         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1761         char *id, *name="", *description="";
1762         float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1763         
1764         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1765                 return NULL;
1766         
1767         if (PyTuple_Size(args) > 0) {
1768                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1769                 return NULL;
1770         }
1771         
1772         if (self) {
1773                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1774                 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1775                 Py_RETURN_NONE;
1776         } else {
1777                 PyObject *ret = PyTuple_New(2);
1778                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1779                 PyTuple_SET_ITEM(ret, 1, kw);
1780                 Py_INCREF(kw);
1781                 return ret;
1782         }
1783 }
1784
1785 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1786 {
1787         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1788         char *id, *name="", *description="";
1789         int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1790         
1791         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1792                 return NULL;
1793         
1794         if (PyTuple_Size(args) > 0) {
1795                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1796                 return NULL;
1797         }
1798         
1799         if (self) {
1800                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1801                 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
1802                 Py_RETURN_NONE;
1803         } else {
1804                 PyObject *ret = PyTuple_New(2);
1805                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1806                 PyTuple_SET_ITEM(ret, 1, kw);
1807                 Py_INCREF(kw);
1808                 return ret;
1809         }
1810 }
1811
1812 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
1813 {
1814         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
1815         char *id, *name="", *description="";
1816         int def=0;
1817         
1818         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
1819                 return NULL;
1820         
1821         if (PyTuple_Size(args) > 0) {
1822                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1823                 return NULL;
1824         }
1825         
1826         if (self) {
1827                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1828                 RNA_def_boolean(srna, id, def, name, description);
1829                 Py_RETURN_NONE;
1830         } else {
1831                 PyObject *ret = PyTuple_New(2);
1832                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1833                 PyTuple_SET_ITEM(ret, 1, kw);
1834                 Py_INCREF(kw);
1835                 return ret;
1836         }
1837 }
1838
1839 /*-------------------- Type Registration ------------------------*/
1840
1841 static int rna_function_arg_count(FunctionRNA *func)
1842 {
1843         const ListBase *lb= RNA_function_defined_parameters(func);
1844         PropertyRNA *parm;
1845         Link *link;
1846         int count= 1;
1847
1848         for(link=lb->first; link; link=link->next) {
1849                 parm= (PropertyRNA*)link;
1850                 if(!(RNA_property_flag(parm) & PROP_RETURN))
1851                         count++;
1852         }
1853         
1854         return count;
1855 }
1856
1857 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
1858 {
1859         const ListBase *lb;
1860         Link *link;
1861         FunctionRNA *func;
1862         PropertyRNA *prop;
1863         StructRNA *srna= dummyptr->type;
1864         const char *class_type= RNA_struct_identifier(srna);
1865         PyObject *py_class= (PyObject*)py_data;
1866         PyObject *base_class= RNA_struct_py_type_get(srna);
1867         PyObject *item, *fitem;
1868         PyObject *py_arg_count;
1869         int i, flag, arg_count, func_arg_count;
1870         char identifier[128];
1871
1872         if (base_class) {
1873                 if (!PyObject_IsSubclass(py_class, base_class)) {
1874                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
1875                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
1876                         Py_XDECREF(name);
1877                         return -1;
1878                 }
1879         }
1880
1881         /* verify callback functions */
1882         lb= RNA_struct_defined_functions(srna);
1883         i= 0;
1884         for(link=lb->first; link; link=link->next) {
1885                 func= (FunctionRNA*)link;
1886                 flag= RNA_function_flag(func);
1887
1888                 if(!(flag & FUNC_REGISTER))
1889                         continue;
1890
1891                 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
1892
1893                 have_function[i]= (item != NULL);
1894                 i++;
1895
1896                 if (item==NULL) {
1897                         if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
1898                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
1899                                 return -1;
1900                         }
1901
1902                         PyErr_Clear();
1903                 }
1904                 else {
1905                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
1906
1907                         if (PyMethod_Check(item))
1908                                 fitem= PyMethod_Function(item); /* py 2.x */
1909                         else
1910                                 fitem= item; /* py 3.x */
1911
1912                         if (PyFunction_Check(fitem)==0) {
1913                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
1914                                 return -1;
1915                         }
1916
1917                         func_arg_count= rna_function_arg_count(func);
1918
1919                         if (func_arg_count >= 0) { /* -1 if we dont care*/
1920                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
1921                                 arg_count = PyLong_AsSsize_t(py_arg_count);
1922                                 Py_DECREF(py_arg_count);
1923
1924                                 if (arg_count != func_arg_count) {
1925                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
1926                                         return -1;
1927                                 }
1928                         }
1929                 }
1930         }
1931
1932         /* verify properties */
1933         lb= RNA_struct_defined_properties(srna);
1934         for(link=lb->first; link; link=link->next) {
1935                 prop= (PropertyRNA*)link;
1936                 flag= RNA_property_flag(prop);
1937
1938                 if(!(flag & PROP_REGISTER))
1939                         continue;
1940
1941                 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
1942                 item = PyObject_GetAttrString(py_class, identifier);
1943
1944                 if (item==NULL) {
1945                         if(strcmp(identifier, "__idname__") == 0) {
1946                                 item= PyObject_GetAttrString(py_class, "__name__");
1947
1948                                 if(item) {
1949                                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
1950
1951                                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
1952                                                 return -1;
1953                                 }
1954                         }
1955
1956                         if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
1957                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
1958                                 return -1;
1959                         }
1960
1961                         PyErr_Clear();
1962                 }
1963                 else {
1964                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
1965
1966                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
1967                                 return -1;
1968                 }
1969         }
1970
1971         return 0;
1972 }
1973
1974 extern void BPY_update_modules( void ); //XXX temp solution
1975
1976 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
1977 {
1978         PyObject *args;
1979         PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
1980         PropertyRNA *pret= NULL, *parm;
1981         ParameterIterator iter;
1982         PointerRNA funcptr;
1983         void *retdata= NULL;
1984         int err= 0, i, flag;
1985
1986         PyGILState_STATE gilstate = PyGILState_Ensure();
1987
1988         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
1989
1990         py_class= RNA_struct_py_type_get(ptr->type);
1991         
1992         item = pyrna_struct_CreatePyObject(ptr);
1993         if(item == NULL) {
1994                 py_class_instance = NULL;
1995         }
1996         else if(item == Py_None) { /* probably wont ever happen but possible */
1997                 Py_DECREF(item);
1998                 py_class_instance = NULL;
1999         }
2000         else {
2001                 args = PyTuple_New(1);
2002                 PyTuple_SET_ITEM(args, 0, item);
2003                 py_class_instance = PyObject_Call(py_class, args, NULL);
2004                 Py_DECREF(args);
2005         }
2006
2007         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2008                 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2009                 flag= RNA_function_flag(func);
2010
2011                 if(item) {
2012                         pret= RNA_function_return(func);
2013                         RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2014
2015                         args = PyTuple_New(rna_function_arg_count(func));
2016                         PyTuple_SET_ITEM(args, 0, py_class_instance);
2017
2018                         RNA_parameter_list_begin(parms, &iter);
2019
2020                         /* parse function parameters */
2021                         for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2022                                 parm= iter.parm;
2023
2024                                 if (parm==pret) {
2025                                         retdata= iter.data;
2026                                         continue;
2027                                 }
2028
2029                                 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2030                                 PyTuple_SET_ITEM(args, i, parmitem);
2031                                 i++;
2032                         }
2033
2034                         ret = PyObject_Call(item, args, NULL);
2035
2036                         Py_DECREF(item);
2037                         Py_DECREF(args);
2038                 }
2039                 else {
2040                         Py_DECREF(py_class_instance);
2041                         PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2042                         err= -1;
2043                 }
2044         }
2045         else {
2046                 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2047                 err= -1;
2048         }
2049
2050         if (ret == NULL) { /* covers py_class_instance failing too */
2051                 PyErr_Print(); /* XXX use reporting api? */
2052                 err= -1;
2053         }
2054         else {
2055                 if(retdata)
2056                         err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2057                 Py_DECREF(ret);
2058         }
2059
2060         PyGILState_Release(gilstate);
2061         
2062         return err;
2063 }
2064
2065 static void bpy_class_free(void *pyob_ptr)
2066 {
2067         if(G.f&G_DEBUG) {
2068                 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2069                         PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2070         }
2071         Py_DECREF((PyObject *)pyob_ptr);
2072 }
2073
2074 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2075 {
2076         bContext *C= NULL;
2077         PyObject *py_class, *item;
2078         ReportList reports;
2079         StructRegisterFunc reg;
2080         BPy_StructRNA *py_srna;
2081         StructRNA *srna;
2082
2083         if(!PyArg_ParseTuple(args, "O:register", &py_class))
2084                 return NULL;
2085         
2086         if(!PyType_Check(py_class)) {
2087                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2088                 return NULL;
2089         }
2090
2091         /* check we got an __rna__ attribute */
2092         item= PyObject_GetAttrString(py_class, "__rna__");
2093
2094         if(!item || !BPy_StructRNA_Check(item)) {
2095                 Py_XDECREF(item);
2096                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2097                 return NULL;
2098         }
2099
2100         /* check the __rna__ attribute has the right type */
2101         Py_DECREF(item);
2102         py_srna= (BPy_StructRNA*)item;
2103
2104         if(py_srna->ptr.type != &RNA_Struct) {
2105                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2106                 return NULL;
2107         }
2108         
2109         /* check that we have a register callback for this type */
2110         reg= RNA_struct_register(py_srna->ptr.data);
2111
2112         if(!reg) {
2113                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2114                 return NULL;
2115         }
2116         
2117         /* get the context, so register callback can do necessary refreshes */
2118         C= BPy_GetContext();
2119
2120         /* call the register callback */
2121         BKE_reports_init(&reports, RPT_PRINT);
2122         srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2123
2124         if(!srna) {
2125                 BPy_reports_to_error(&reports);
2126                 BKE_reports_clear(&reports);
2127                 return NULL;
2128         }
2129
2130         BKE_reports_clear(&reports);
2131
2132         pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2133
2134         Py_RETURN_NONE;
2135 }
2136
2137 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2138 {
2139         bContext *C= NULL;
2140         PyObject *py_class, *item;
2141         BPy_StructRNA *py_srna;
2142         StructUnregisterFunc unreg;
2143
2144         if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2145                 return NULL;
2146
2147         if(!PyType_Check(py_class)) {
2148                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2149                 return NULL;
2150         }
2151
2152         /* check we got an __rna__ attribute */
2153         item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__");  /* borrow ref */
2154
2155         if(!item || !BPy_StructRNA_Check(item)) {
2156                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2157                 return NULL;
2158         }
2159
2160         /* check the __rna__ attribute has the right type */
2161         py_srna= (BPy_StructRNA*)item;
2162
2163         if(py_srna->ptr.type != &RNA_Struct) {
2164                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2165                 return NULL;
2166         }
2167         
2168         /* check that we have a unregister callback for this type */
2169         unreg= RNA_struct_unregister(py_srna->ptr.data);
2170
2171         if(!unreg) {
2172                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2173                 return NULL;
2174         }
2175         
2176         /* get the context, so register callback can do necessary refreshes */
2177         C= BPy_GetContext();
2178         
2179
2180         /* call unregister */
2181         unreg(C, py_srna->ptr.data);
2182
2183         /* remove reference to old type */
2184         Py_DECREF(py_class);
2185
2186         Py_RETURN_NONE;
2187 }
2188