Cleanup: style
[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, options=set())\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 "   :arg options: Change the behavior of the subscriber.\n"
224 "\n"
225 "      - ``PERSISTENT`` when set, the subscriber will be kept when remapping ID data.\n"
226 "\n"
227 "   :type options: set of str.\n"
228 "\n"
229 "   Returns a new vector int property definition.\n"
230 );
231 static PyObject *bpy_msgbus_subscribe_rna(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
232 {
233         const char *error_prefix = "subscribe_rna";
234         PyObject *py_sub = NULL;
235         PyObject *py_owner = NULL;
236         PyObject *callback_args = NULL;
237         PyObject *callback_notify = NULL;
238
239         enum {
240                 IS_PERSISTENT = (1 << 0),
241         };
242         PyObject *py_options = NULL;
243         EnumPropertyItem py_options_enum[] = {
244                 {IS_PERSISTENT, "PERSISTENT", 0, ""},
245                 {0, NULL, 0, NULL, NULL},
246         };
247         int options = 0;
248
249         if (PyTuple_GET_SIZE(args) != 0) {
250                 PyErr_Format(
251                         PyExc_TypeError,
252                         "%s: only keyword arguments are supported",
253                         error_prefix);
254                 return NULL;
255         }
256         static const char *_keywords[] = {
257                 "key",
258                 "owner",
259                 "args",
260                 "notify",
261                 "options",
262                 NULL,
263         };
264         static _PyArg_Parser _parser = {"OOO!O|O!:subscribe_rna", _keywords, 0};
265         if (!_PyArg_ParseTupleAndKeywordsFast(
266                 args, kw, &_parser,
267                 &py_sub, &py_owner,
268                 &PyTuple_Type, &callback_args,
269                 &callback_notify,
270                 &PySet_Type, &py_options))
271         {
272                 return NULL;
273         }
274
275         if (py_options &&
276             (pyrna_set_to_enum_bitfield(py_options_enum, py_options, &options, error_prefix)) == -1)
277         {
278                 return NULL;
279         }
280
281         /* Note: we may want to have a way to pass this in. */
282         bContext *C = (bContext *)BPy_GetContext();
283         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
284         wmMsgParams_RNA msg_key_params = {{{0}}};
285
286         wmMsgSubscribeValue msg_val_params = {0};
287
288         if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
289                 return NULL;
290         }
291
292         if (!PyFunction_Check(callback_notify)) {
293                 PyErr_Format(
294                         PyExc_TypeError,
295                         "notify expects a function, found %.200s",
296                         Py_TYPE(callback_notify)->tp_name);
297                 return NULL;
298         }
299
300         if (options != 0) {
301                 if (options & IS_PERSISTENT) {
302                         msg_val_params.is_persistent = true;
303                 }
304         }
305
306         /* owner can be anything. */
307         {
308                 msg_val_params.owner = py_owner;
309                 Py_INCREF(py_owner);
310         }
311
312         {
313                 PyObject *user_data = PyTuple_New(2);
314                 PyTuple_SET_ITEMS(
315                         user_data,
316                         Py_INCREF_RET(callback_args),
317                         Py_INCREF_RET(callback_notify));
318                 msg_val_params.user_data = user_data;
319         }
320
321         msg_val_params.notify = bpy_msgbus_notify;
322         msg_val_params.free_data = bpy_msgbus_subscribe_value_free_data;
323
324         WM_msg_subscribe_rna_params(mbus, &msg_key_params, &msg_val_params, __func__);
325
326         WM_msg_dump(mbus, __func__);
327
328         Py_RETURN_NONE;
329 }
330
331 PyDoc_STRVAR(bpy_msgbus_publish_rna_doc,
332 ".. function:: publish_rna(data, owner, args, notify)\n"
333 "\n"
334 BPY_MSGBUS_RNA_MSGKEY_DOC
335 "\n"
336 "   Notify subscribers of changes to this property\n"
337 "   (this typically doesn't need to be called explicitly since changes will automatically publish updates).\n"
338 "   In some cases it may be useful to publish changes explicitly using more general keys.\n"
339 );
340 static PyObject *bpy_msgbus_publish_rna(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
341 {
342         const char *error_prefix = "publish_rna";
343         PyObject *py_sub = NULL;
344
345         if (PyTuple_GET_SIZE(args) != 0) {
346                 PyErr_Format(
347                         PyExc_TypeError,
348                         "%s: only keyword arguments are supported",
349                         error_prefix);
350                 return NULL;
351         }
352         static const char *_keywords[] = {
353                 "key",
354                 NULL,
355         };
356         static _PyArg_Parser _parser = {"O:publish_rna", _keywords, 0};
357         if (!_PyArg_ParseTupleAndKeywordsFast(
358                 args, kw, &_parser,
359                 &py_sub))
360         {
361                 return NULL;
362         }
363
364         /* Note: we may want to have a way to pass this in. */
365         bContext *C = (bContext *)BPy_GetContext();
366         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
367         wmMsgParams_RNA msg_key_params = {{{0}}};
368
369         if (py_msgbus_rna_key_from_py(py_sub, &msg_key_params, error_prefix) == -1) {
370                 return NULL;
371         }
372
373         WM_msg_publish_rna_params(mbus, &msg_key_params);
374
375         Py_RETURN_NONE;
376 }
377
378 PyDoc_STRVAR(bpy_msgbus_clear_by_owner_doc,
379 ".. function:: clear_by_owner(owner)\n"
380 "\n"
381 "   Clear all subscribers using this owner.\n"
382 );
383 static PyObject *bpy_msgbus_clear_by_owner(PyObject *UNUSED(self), PyObject *py_owner)
384 {
385         bContext *C = (bContext *)BPy_GetContext();
386         struct wmMsgBus *mbus = CTX_wm_message_bus(C);
387         WM_msgbus_clear_by_owner(mbus, py_owner);
388         Py_RETURN_NONE;
389 }
390
391 static struct PyMethodDef BPy_msgbus_methods[] = {
392         {"subscribe_rna", (PyCFunction)bpy_msgbus_subscribe_rna, METH_VARARGS | METH_KEYWORDS, bpy_msgbus_subscribe_rna_doc},
393         {"publish_rna", (PyCFunction)bpy_msgbus_publish_rna, METH_VARARGS | METH_KEYWORDS, bpy_msgbus_publish_rna_doc},
394         {"clear_by_owner", (PyCFunction)bpy_msgbus_clear_by_owner, METH_O, bpy_msgbus_clear_by_owner_doc},
395         {NULL, NULL, 0, NULL},
396 };
397
398 static struct PyModuleDef _bpy_msgbus_def = {
399         PyModuleDef_HEAD_INIT,
400         .m_name = "msgbus",
401         .m_methods = BPy_msgbus_methods,
402 };
403
404
405 PyObject *BPY_msgbus_module(void)
406 {
407         PyObject *submodule;
408
409         submodule = PyModule_Create(&_bpy_msgbus_def);
410
411         return submodule;
412 }
413
414 /** \} */