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