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