use ghash for operator and menu types, was doing string lookup in the operator list...
[blender.git] / source / blender / python / intern / bpy_operator.c
1
2 /*
3  * $Id$
4  *
5  * ***** BEGIN GPL LICENSE BLOCK *****
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  * Contributor(s): Campbell Barton
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/python/intern/bpy_operator.c
27  *  \ingroup pythonintern
28  */
29
30
31 /* Note, this module is not to be used directly by the user.
32  * Internally its exposed as '_bpy.ops', which provides functions for 'bpy.ops', a python package.
33  * */
34
35 #include <Python.h>
36
37 #include "RNA_types.h"
38
39 #include "BPY_extern.h"
40 #include "bpy_operator.h"
41 #include "bpy_operator_wrap.h"
42 #include "bpy_rna.h" /* for setting arg props only - pyrna_py_to_prop() */
43 #include "bpy_util.h"
44 #include "../generic/bpy_internal_import.h"
45
46 #include "BLI_utildefines.h"
47
48 #include "RNA_access.h"
49 #include "RNA_enum_types.h"
50
51 #include "WM_api.h"
52 #include "WM_types.h"
53
54 #include "MEM_guardedalloc.h"
55
56 #include "BLI_ghash.h"
57
58 #include "BKE_report.h"
59 #include "BKE_context.h"
60
61 /* so operators called can spawn threads which aquire the GIL */
62 #define BPY_RELEASE_GIL
63
64
65 static PyObject *pyop_poll(PyObject *UNUSED(self), PyObject *args)
66 {
67         wmOperatorType *ot;
68         char            *opname;
69         PyObject        *context_dict= NULL; /* optional args */
70         PyObject        *context_dict_back;
71         char            *context_str= NULL;
72         PyObject        *ret;
73
74         int context= WM_OP_EXEC_DEFAULT;
75
76         // XXX Todo, work out a better solution for passing on context, could make a tuple from self and pack the name and Context into it...
77         bContext *C= (bContext *)BPy_GetContext();
78         
79         if(C==NULL) {
80                 PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
81                 return NULL;
82         }
83
84         if (!PyArg_ParseTuple(args, "s|Os:_bpy.ops.poll", &opname, &context_dict, &context_str))
85                 return NULL;
86         
87         ot= WM_operatortype_find(opname, TRUE);
88
89         if (ot == NULL) {
90                 PyErr_Format(PyExc_AttributeError,
91                              "Polling operator \"bpy.ops.%s\" error, "
92                              "could not be found", opname);
93                 return NULL;
94         }
95
96         if(context_str) {
97                 if(RNA_enum_value_from_id(operator_context_items, context_str, &context)==0) {
98                         char *enum_str= BPy_enum_as_string(operator_context_items);
99                         PyErr_Format(PyExc_TypeError,
100                                      "Calling operator \"bpy.ops.%s.poll\" error, "
101                                      "expected a string enum in (%.200s)",
102                                      opname, enum_str);
103                         MEM_freeN(enum_str);
104                         return NULL;
105                 }
106         }
107         
108         if(context_dict==NULL || context_dict==Py_None) {
109                 context_dict= NULL;
110         }
111         else if (!PyDict_Check(context_dict)) {
112                 PyErr_Format(PyExc_TypeError,
113                              "Calling operator \"bpy.ops.%s.poll\" error, "
114                              "custom context expected a dict or None, got a %.200s",
115                              opname, Py_TYPE(context_dict)->tp_name);
116                 return NULL;
117         }
118
119         context_dict_back= CTX_py_dict_get(C);
120
121         CTX_py_dict_set(C, (void *)context_dict);
122         Py_XINCREF(context_dict); /* so we done loose it */
123         
124         /* main purpose of thsi function */
125         ret= WM_operator_poll_context((bContext*)C, ot, context) ? Py_True : Py_False;
126         
127         /* restore with original context dict, probably NULL but need this for nested operator calls */
128         Py_XDECREF(context_dict);
129         CTX_py_dict_set(C, (void *)context_dict_back);
130         
131         Py_INCREF(ret);
132         return ret;
133 }
134
135 static PyObject *pyop_call(PyObject *UNUSED(self), PyObject *args)
136 {
137         wmOperatorType *ot;
138         int error_val= 0;
139         PointerRNA ptr;
140         int operator_ret= OPERATOR_CANCELLED;
141
142         char            *opname;
143         char            *context_str= NULL;
144         PyObject        *kw= NULL; /* optional args */
145         PyObject        *context_dict= NULL; /* optional args */
146         PyObject        *context_dict_back;
147
148         /* note that context is an int, python does the conversion in this case */
149         int context= WM_OP_EXEC_DEFAULT;
150
151         // XXX Todo, work out a better solution for passing on context, could make a tuple from self and pack the name and Context into it...
152         bContext *C= (bContext *)BPy_GetContext();
153         
154         if(C==NULL) {
155                 PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
156                 return NULL;
157         }
158         
159         if (!PyArg_ParseTuple(args, "sO|O!s:_bpy.ops.call", &opname, &context_dict, &PyDict_Type, &kw, &context_str))
160                 return NULL;
161
162         ot= WM_operatortype_find(opname, TRUE);
163
164         if (ot == NULL) {
165                 PyErr_Format(PyExc_AttributeError,
166                              "Calling operator \"bpy.ops.%s\" error, "
167                              "could not be found", opname);
168                 return NULL;
169         }
170         
171         if(!pyrna_write_check()) {
172                 PyErr_Format(PyExc_RuntimeError,
173                              "Calling operator \"bpy.ops.%s\" error, "
174                              "can't modify blend data in this state (drawing/rendering)",
175                              opname);
176                 return NULL;
177         }
178
179         if(context_str) {
180                 if(RNA_enum_value_from_id(operator_context_items, context_str, &context)==0) {
181                         char *enum_str= BPy_enum_as_string(operator_context_items);
182                         PyErr_Format(PyExc_TypeError,
183                                      "Calling operator \"bpy.ops.%s\" error, "
184                                      "expected a string enum in (%.200s)",
185                                      opname, enum_str);
186                         MEM_freeN(enum_str);
187                         return NULL;
188                 }
189         }
190
191         if(context_dict==NULL || context_dict==Py_None) {
192                 context_dict= NULL;
193         }
194         else if (!PyDict_Check(context_dict)) {
195                 PyErr_Format(PyExc_TypeError,
196                              "Calling operator \"bpy.ops.%s\" error, "
197                              "custom context expected a dict or None, got a %.200s",
198                              opname, Py_TYPE(context_dict)->tp_name);
199                 return NULL;
200         }
201
202         context_dict_back= CTX_py_dict_get(C);
203
204         CTX_py_dict_set(C, (void *)context_dict);
205         Py_XINCREF(context_dict); /* so we done loose it */
206
207         if(WM_operator_poll_context((bContext*)C, ot, context) == FALSE) {
208                 const char *msg= CTX_wm_operator_poll_msg_get(C);
209                 PyErr_Format(PyExc_RuntimeError,
210                              "Operator bpy.ops.%.200s.poll() %.200s",
211                              opname, msg ? msg : "failed, context is incorrect");
212                 CTX_wm_operator_poll_msg_set(C, NULL); /* better set to NULL else it could be used again */
213                 error_val= -1;
214         }
215         else {
216                 WM_operator_properties_create_ptr(&ptr, ot);
217                 WM_operator_properties_sanitize(&ptr, 0);
218
219                 if(kw && PyDict_Size(kw))
220                         error_val= pyrna_pydict_to_props(&ptr, kw, 0, "Converting py args to operator properties: ");
221
222
223                 if (error_val==0) {
224                         ReportList *reports;
225
226                         reports= MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
227                         BKE_reports_init(reports, RPT_STORE | RPT_OP_HOLD); /* own so these dont move into global reports */
228
229 #ifdef BPY_RELEASE_GIL
230                         /* release GIL, since a thread could be started from an operator
231                          * that updates a driver */
232                         /* note: I havve not seen any examples of code that does this
233                          * so it may not be officially supported but seems to work ok. */
234                         {
235                                 PyThreadState *ts= PyEval_SaveThread();
236 #endif
237
238                                 operator_ret= WM_operator_call_py(C, ot, context, &ptr, reports);
239
240 #ifdef BPY_RELEASE_GIL
241                                 /* regain GIL */
242                                 PyEval_RestoreThread(ts);
243                         }
244 #endif
245
246                         error_val= BPy_reports_to_error(reports, PyExc_RuntimeError, FALSE);
247
248                         /* operator output is nice to have in the terminal/console too */
249                         if(reports->list.first) {
250                                 char *report_str= BKE_reports_string(reports, 0); /* all reports */
251         
252                                 if(report_str) {
253                                         PySys_WriteStdout("%s\n", report_str);
254                                         MEM_freeN(report_str);
255                                 }
256                         }
257         
258                         BKE_reports_clear(reports);
259                         if ((reports->flag & RPT_FREE) == 0)
260                         {
261                                 MEM_freeN(reports);
262                         }
263                 }
264
265                 WM_operator_properties_free(&ptr);
266
267 #if 0
268                 /* if there is some way to know an operator takes args we should use this */
269                 {
270                         /* no props */
271                         if (kw != NULL) {
272                                 PyErr_Format(PyExc_AttributeError,
273                                              "Operator \"%s\" does not take any args",
274                                              opname);
275                                 return NULL;
276                         }
277
278                         WM_operator_name_call(C, opname, WM_OP_EXEC_DEFAULT, NULL);
279                 }
280 #endif
281         }
282
283         /* restore with original context dict, probably NULL but need this for nested operator calls */
284         Py_XDECREF(context_dict);
285         CTX_py_dict_set(C, (void *)context_dict_back);
286
287         if (error_val==-1) {
288                 return NULL;
289         }
290
291         /* when calling  bpy.ops.wm.read_factory_settings() bpy.data's main pointer is freed by clear_globals(),
292          * further access will crash blender. setting context is not needed in this case, only calling because this
293          * function corrects bpy.data (internal Main pointer) */
294         BPY_modules_update(C);
295
296         /* needed for when WM_OT_read_factory_settings us called fro within a script */
297         bpy_import_main_set(CTX_data_main(C));
298
299         /* return operator_ret as a bpy enum */
300         return pyrna_enum_bitfield_to_py(operator_return_items, operator_ret);
301
302 }
303
304 static PyObject *pyop_as_string(PyObject *UNUSED(self), PyObject *args)
305 {
306         wmOperatorType *ot;
307         PointerRNA ptr;
308
309         char            *opname;
310         PyObject        *kw= NULL; /* optional args */
311         int all_args= 1;
312         int error_val= 0;
313
314         char *buf= NULL;
315         PyObject *pybuf;
316
317         bContext *C= (bContext *)BPy_GetContext();
318
319         if(C==NULL) {
320                 PyErr_SetString(PyExc_RuntimeError, "Context is None, cant get the string representation of this object.");
321                 return NULL;
322         }
323         
324         if (!PyArg_ParseTuple(args, "s|O!i:_bpy.ops.as_string", &opname, &PyDict_Type, &kw, &all_args))
325                 return NULL;
326
327         ot= WM_operatortype_find(opname, TRUE);
328
329         if (ot == NULL) {
330                 PyErr_Format(PyExc_AttributeError,
331                              "_bpy.ops.as_string: operator \"%.200s\" "
332                              "could not be found", opname);
333                 return NULL;
334         }
335
336         /* WM_operator_properties_create(&ptr, opname); */
337         /* Save another lookup */
338         RNA_pointer_create(NULL, ot->srna, NULL, &ptr);
339
340         if(kw && PyDict_Size(kw))
341                 error_val= pyrna_pydict_to_props(&ptr, kw, 0, "Converting py args to operator properties: ");
342
343         if (error_val==0)
344                 buf= WM_operator_pystring(C, ot, &ptr, all_args);
345
346         WM_operator_properties_free(&ptr);
347
348         if (error_val==-1) {
349                 return NULL;
350         }
351
352         if(buf) {
353                 pybuf= PyUnicode_FromString(buf);
354                 MEM_freeN(buf);
355         }
356         else {
357                 pybuf= PyUnicode_FromString("");
358         }
359
360         return pybuf;
361 }
362
363 static PyObject *pyop_dir(PyObject *UNUSED(self))
364 {
365         GHashIterator *iter= WM_operatortype_iter();
366         PyObject *list= PyList_New(0), *name;
367
368         for( ; !BLI_ghashIterator_isDone(iter); BLI_ghashIterator_step(iter)) {
369                 wmOperatorType *ot= BLI_ghashIterator_getValue(iter);
370
371                 name= PyUnicode_FromString(ot->idname);
372                 PyList_Append(list, name);
373                 Py_DECREF(name);
374         }
375         BLI_ghashIterator_free(iter);
376
377         return list;
378 }
379
380 static PyObject *pyop_getrna(PyObject *UNUSED(self), PyObject *value)
381 {
382         wmOperatorType *ot;
383         PointerRNA ptr;
384         char *opname= _PyUnicode_AsString(value);
385         BPy_StructRNA *pyrna= NULL;
386         
387         if(opname==NULL) {
388                 PyErr_SetString(PyExc_TypeError, "_bpy.ops.get_rna() expects a string argument");
389                 return NULL;
390         }
391         ot= WM_operatortype_find(opname, TRUE);
392         if(ot==NULL) {
393                 PyErr_Format(PyExc_KeyError, "_bpy.ops.get_rna(\"%s\") not found", opname);
394                 return NULL;
395         }
396         
397         /* type */
398         //RNA_pointer_create(NULL, &RNA_Struct, ot->srna, &ptr);
399
400         /* XXX - should call WM_operator_properties_free */
401         WM_operator_properties_create_ptr(&ptr, ot);
402         WM_operator_properties_sanitize(&ptr, 0);
403
404         
405         pyrna= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
406 #ifdef PYRNA_FREE_SUPPORT
407         pyrna->freeptr= TRUE;
408 #endif
409         return (PyObject *)pyrna;
410 }
411
412 static struct PyMethodDef bpy_ops_methods[]= {
413         {"poll", (PyCFunction) pyop_poll, METH_VARARGS, NULL},
414         {"call", (PyCFunction) pyop_call, METH_VARARGS, NULL},
415         {"as_string", (PyCFunction) pyop_as_string, METH_VARARGS, NULL},
416         {"dir", (PyCFunction) pyop_dir, METH_NOARGS, NULL},
417         {"get_rna", (PyCFunction) pyop_getrna, METH_O, NULL},
418         {"macro_define", (PyCFunction) PYOP_wrap_macro_define, METH_VARARGS, NULL},
419         {NULL, NULL, 0, NULL}
420 };
421
422 static struct PyModuleDef bpy_ops_module= {
423         PyModuleDef_HEAD_INIT,
424         "_bpy.ops",
425         NULL,
426         -1,/* multiple "initialization" just copies the module dict. */
427         bpy_ops_methods,
428         NULL, NULL, NULL, NULL
429 };
430
431 PyObject *BPY_operator_module(void)
432 {
433         PyObject *submodule;
434
435         submodule= PyModule_Create(&bpy_ops_module);
436
437         return submodule;
438 }