Merge branch 'blender2.7'
[blender.git] / source / blender / python / intern / bpy_msgbus.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16
17 /** \file
18  * \ingroup pythonintern
19  * This file defines '_bpy_msgbus' module, exposed as 'bpy.msgbus'.
20  */
21
22 #include <Python.h>
23
24 #include "../generic/python_utildefines.h"
25 #include "../generic/py_capi_utils.h"
26 #include "../mathutils/mathutils.h"
27
28 #include "BLI_utildefines.h"
29
30 #include "BKE_context.h"
31
32 #include "WM_api.h"
33 #include "WM_types.h"
34 #include "WM_message.h"
35
36 #include "RNA_access.h"
37 #include "RNA_define.h"
38 #include "RNA_enum_types.h"
39
40 #include "bpy_capi_utils.h"
41 #include "bpy_rna.h"
42 #include "bpy_intern_string.h"
43 #include "bpy_gizmo_wrap.h"  /* own include */
44
45
46 #include "bpy_msgbus.h"  /* own include */
47
48
49 /* -------------------------------------------------------------------- */
50 /** \name Internal Utils
51  * \{ */
52
53 #define BPY_MSGBUS_RNA_MSGKEY_DOC \
54 "   :arg key: Represents the type of data being subscribed to\n" \
55 "\n" \
56 "      Arguments include\n" \
57 "      - :class:`bpy.types.Property` instance.\n" \
58 "      - :class:`bpy.types.Struct` type.\n" \
59 "      - (:class:`bpy.types.Struct`, str) type and property name.\n" \
60 "   :type key: Muliple\n"
61
62 /**
63  * There are multiple ways we can get RNA from Python,
64  * it's also possible to register a type instead of an instance.
65  *
66  * This function handles converting Python to RNA subscription information.
67  *
68  * \param py_sub: See #BPY_MSGBUS_RNA_MSGKEY_DOC for description.
69  * \param msg_key_params: Message key with all members zeroed out.
70  * \return -1 on failure, 0 on success.
71  */
72 static int py_msgbus_rna_key_from_py(
73         PyObject *py_sub,
74         wmMsgParams_RNA *msg_key_params,
75         const char *error_prefix)
76 {
77
78         /* Allow common case, object rotation, location - etc. */
79         if (BaseMathObject_CheckExact(py_sub)) {
80                 BaseMathObject *py_sub_math = (BaseMathObject *)py_sub;
81                 if (py_sub_math->cb_user == NULL) {
82                         PyErr_Format(
83                                 PyExc_TypeError,
84                                 "%s: math argument has no owner",
85                                 error_prefix);
86                         return -1;
87                 }
88                 py_sub = py_sub_math->cb_user;
89                 /* Common case will use BPy_PropertyRNA_Check below. */
90         }
91
92         if (BPy_PropertyRNA_Check(py_sub)) {
93                 BPy_PropertyRNA *data_prop = (BPy_PropertyRNA *)py_sub;
94                 PYRNA_PROP_CHECK_INT(data_prop);
95                 msg_key_params->ptr = data_prop->ptr;
96                 msg_key_params->prop = data_prop->prop;
97         }
98         else if (BPy_StructRNA_Check(py_sub)) {
99                 /* note, this isn't typically used since we don't edit structs directly. */
100                 BPy_StructRNA *data_srna = (BPy_StructRNA *)py_sub;
101                 PYRNA_STRUCT_CHECK_INT(data_srna);
102                 msg_key_params->ptr = data_srna->ptr;
103         }
104         /* TODO - property / type, not instance. */
105         else if (PyType_Check(py_sub)) {
106                 StructRNA *data_type = pyrna_struct_as_srna(py_sub, false, error_prefix);
107                 if (data_type == NULL) {
108                         return -1;
109                 }
110                 msg_key_params->ptr.type = data_type;
111         }
112         else if (PyTuple_CheckExact(py_sub)) {
113                 if (PyTuple_GET_SIZE(py_sub) == 2) {
114                         PyObject *data_type_py = PyTuple_GET_ITEM(py_sub, 0);
115                         PyObject *data_prop_py = PyTuple_GET_ITEM(py_sub, 1);
116                         StructRNA *data_type = pyrna_struct_as_srna(data_type_py, false, error_prefix);
117                         if (data_type == NULL) {
118                                 return -1;
119                         }
120                         if (!PyUnicode_CheckExact(data_prop_py)) {
121                                 PyErr_Format(
122                                         PyExc_TypeError,
123                                         "%s: expected property to be a string",
124                                         error_prefix);
125                                 return -1;
126                         }
127                         PointerRNA data_type_ptr = { .type = data_type, };
128                         const char *data_prop_str = _PyUnicode_AsString(data_prop_py);
129                         PropertyRNA *data_prop = RNA_struct_find_property(&data_type_ptr, data_prop_str);
130
131                         if (data_prop == NULL) {
132                                 PyErr_Format(
133                                         PyExc_TypeError,
134                                         "%s: struct %.200s does not contain property %.200s",
135                                         error_prefix,
136                                         RNA_struct_identifier(data_type),
137                                         data_prop_str);
138                                 return -1;
139                         }
140
141                         msg_key_params->ptr.type = data_type;
142                         msg_key_params->prop = data_prop;
143                 }
144                 else {
145                         PyErr_Format(
146                                 PyExc_ValueError,
147                                 "%s: Expected a pair (type, property_id)",
148                                 error_prefix);
149                         return -1;
150                 }
151         }
152         return 0;
153 }
154
155 /** \} */
156
157 /* -------------------------------------------------------------------- */
158 /** \name Internal Callbacks
159  * \{ */
160
161 #define BPY_MSGBUS_USER_DATA_LEN 2
162
163 /* Follow wmMsgNotifyFn spec */
164 static void bpy_msgbus_notify(
165         bContext *C, wmMsgSubscribeKey *UNUSED(msg_key), wmMsgSubscribeValue *msg_val)
166 {
167         PyGILState_STATE gilstate;
168         bpy_context_set(C, &gilstate);
169
170         PyObject *user_data = msg_val->user_data;
171         BLI_assert(PyTuple_GET_SIZE(user_data) == BPY_MSGBUS_USER_DATA_LEN);
172
173         PyObject *callback_args = PyTuple_GET_ITEM(user_data, 0);
174         PyObject *callback_notify = PyTuple_GET_ITEM(user_data, 1);
175
176         const bool is_write_ok = pyrna_write_check();
177         if (!is_write_ok) {
178                 pyrna_write_set(true);
179         }
180
181         PyObject *ret = PyObject_CallObject(callback_notify, callback_args);
182
183         if (ret == NULL) {
184                 PyC_Err_PrintWithFunc(callback_notify);
185         }
186         else {
187                 if (ret != Py_None) {
188                         PyErr_SetString(PyExc_ValueError, "the return value must be None");
189                         PyC_Err_PrintWithFunc(callback_notify);
190                 }
191                 Py_DECREF(ret);
192         }
193
194         bpy_context_clear(C, &gilstate);
195
196         if (!is_write_ok) {
197                 pyrna_write_set(false);
198         }
199 }
200
201 /* Follow wmMsgSubscribeValueFreeDataFn spec */
202 static void bpy_msgbus_subscribe_value_free_data(
203         struct wmMsgSubscribeKey *UNUSED(msg_key), struct wmMsgSubscribeValue *msg_val)
204 {
205         PyGILState_STATE gilstate = PyGILState_Ensure();
206         Py_DECREF(msg_val->owner);
207         Py_DECREF(msg_val->user_data);
208         PyGILState_Release(gilstate);
209 }
210
211 /** \} */
212
213 /* -------------------------------------------------------------------- */
214 /** \name Public Message Bus API
215  * \{ */
216
217 PyDoc_STRVAR(bpy_msgbus_subscribe_rna_doc,
218 ".. function:: subscribe_rna(data, owner, args, notify)\n"
219 "\n"
220 BPY_MSGBUS_RNA_MSGKEY_DOC
221 "   :arg owner: Handle for this subscription (compared by identity).\n"
222 "   :type owner: Any type.\n"
223 "\n"
224 "   Returns a new vector int property definition.\n"
225 );
226 static PyObject *bpy_msgbus_subscribe_rna(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
227 {
228         const char *error_prefix = "subscribe_rna";
229         PyObject *py_sub = NULL;
230         PyObject *py_owner = NULL;
231         PyObject *callback_args = NULL;
232         PyObject *callback_notify = NULL;
233
234         enum {
235                 IS_PERSISTENT = (1 << 0),
236         };
237         PyObject *py_options = NULL;
238         EnumPropertyItem py_options_enum[] = {
239                 {IS_PERSISTENT, "PERSISTENT", 0, ""},
240                 {0, NULL, 0, NULL, NULL},
241         };
242         int options = 0;
243
244         static const char *_keywords[] = {
245                 "key",
246                 "owner",
247                 "args",
248                 "notify",
249                 "options",
250                 NULL,
251         };
252         static _PyArg_Parser _parser = {"$OOO!O|O!:subscribe_rna", _keywords, 0};
253         if (!_PyArg_ParseTupleAndKeywordsFast(
254                 args, kw, &_parser,
255                 &py_sub, &py_owner,
256                 &PyTuple_Type, &callback_args,
257                 &callback_notify,
258                 &PySet_Type, &py_options))
259         {
260                 return NULL;
261         }
262
263         if (py_options &&
264             (pyrna_set_to_enum_bitfield(py_options_enum, py_options, &options, error_prefix)) == -1)
265         {
266                 return NULL;
267         }
268
269         /* Note: we may want to have a way to pass this in. */
270         bContext *C = (bContext *)BPy_GetContext();
271         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
272         wmMsgParams_RNA msg_key_params = {{{0}}};
273
274         wmMsgSubscribeValue msg_val_params = {0};
275
276         if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
277                 return NULL;
278         }
279
280         if (!PyFunction_Check(callback_notify)) {
281                 PyErr_Format(
282                         PyExc_TypeError,
283                         "notify expects a function, found %.200s",
284                         Py_TYPE(callback_notify)->tp_name);
285                 return NULL;
286         }
287
288         if (options != 0) {
289                 if (options & IS_PERSISTENT) {
290                         msg_val_params.is_persistent = true;
291                 }
292         }
293
294         /* owner can be anything. */
295         {
296                 msg_val_params.owner = py_owner;
297                 Py_INCREF(py_owner);
298         }
299
300         {
301                 PyObject *user_data = PyTuple_New(2);
302                 PyTuple_SET_ITEMS(
303                         user_data,
304                         Py_INCREF_RET(callback_args),
305                         Py_INCREF_RET(callback_notify));
306                 msg_val_params.user_data = user_data;
307         }
308
309         msg_val_params.notify = bpy_msgbus_notify;
310         msg_val_params.free_data = bpy_msgbus_subscribe_value_free_data;
311
312         WM_msg_subscribe_rna_params(mbus, &msg_key_params, &msg_val_params, __func__);
313
314         WM_msg_dump(mbus, __func__);
315
316         Py_RETURN_NONE;
317 }
318
319 PyDoc_STRVAR(bpy_msgbus_publish_rna_doc,
320 ".. function:: publish_rna(data, owner, args, notify)\n"
321 "\n"
322 BPY_MSGBUS_RNA_MSGKEY_DOC
323 "\n"
324 "   Notify subscribers of changes to this property\n"
325 "   (this typically doesn't need to be called explicitly since changes will automatically publish updates).\n"
326 "   In some cases it may be useful to publish changes explicitly using more general keys.\n"
327 );
328 static PyObject *bpy_msgbus_publish_rna(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
329 {
330         const char *error_prefix = "publish_rna";
331         PyObject *py_sub = NULL;
332
333         static const char *_keywords[] = {
334                 "key",
335                 NULL,
336         };
337         static _PyArg_Parser _parser = {"$O:publish_rna", _keywords, 0};
338         if (!_PyArg_ParseTupleAndKeywordsFast(
339                 args, kw, &_parser,
340                 &py_sub))
341         {
342                 return NULL;
343         }
344
345         /* Note: we may want to have a way to pass this in. */
346         bContext *C = (bContext *)BPy_GetContext();
347         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
348         wmMsgParams_RNA msg_key_params = {{{0}}};
349
350         if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
351                 return NULL;
352         }
353
354         WM_msg_publish_rna_params(mbus, &msg_key_params);
355
356         Py_RETURN_NONE;
357 }
358
359 PyDoc_STRVAR(bpy_msgbus_clear_by_owner_doc,
360 ".. function:: clear_by_owner(owner)\n"
361 "\n"
362 "   Clear all subscribers using this owner.\n"
363 );
364 static PyObject *bpy_msgbus_clear_by_owner(PyObject *UNUSED(self), PyObject *py_owner)
365 {
366         bContext *C = (bContext *)BPy_GetContext();
367         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
368         WM_msgbus_clear_by_owner(mbus, py_owner);
369         Py_RETURN_NONE;
370 }
371
372 static struct PyMethodDef BPy_msgbus_methods[] = {
373         {"subscribe_rna", (PyCFunction)bpy_msgbus_subscribe_rna, METH_VARARGS | METH_KEYWORDS, bpy_msgbus_subscribe_rna_doc},
374         {"publish_rna", (PyCFunction)bpy_msgbus_publish_rna, METH_VARARGS | METH_KEYWORDS, bpy_msgbus_publish_rna_doc},
375         {"clear_by_owner", (PyCFunction)bpy_msgbus_clear_by_owner, METH_O, bpy_msgbus_clear_by_owner_doc},
376         {NULL, NULL, 0, NULL},
377 };
378
379 static struct PyModuleDef _bpy_msgbus_def = {
380         PyModuleDef_HEAD_INIT,
381         .m_name = "msgbus",
382         .m_methods = BPy_msgbus_methods,
383 };
384
385
386 PyObject *BPY_msgbus_module(void)
387 {
388         PyObject *submodule;
389
390         submodule = PyModule_Create(&_bpy_msgbus_def);
391
392         return submodule;
393 }
394
395 /** \} */