Blender V5.3
bpy_operator_function.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
11
12#include <Python.h>
13#include <optional>
14
16#include "RNA_types.hh"
17
18#include "BLI_listbase.hh"
19#include "BLI_string.hh"
20
23#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
24
25#include "BPY_extern.hh"
26#include "bpy_capi_utils.hh"
28#include "bpy_rna.hh" /* for setting argument properties & type method `get_rna_type`. */
29
30#include "RNA_access.hh"
31#include "RNA_enum_types.hh"
32#include "RNA_prototypes.hh"
33
34#include "WM_api.hh"
35#include "WM_types.hh"
36
37#include "MEM_guardedalloc.h"
38
39#include "BKE_context.hh"
40#include "BKE_layer.hh"
41#include "BKE_main.hh"
42#include "BKE_report.hh"
43#include "BKE_scene.hh"
44
45#include "DNA_scene_types.h"
46
47#include "DEG_depsgraph.hh"
48
49#include "CLG_log.h"
50
51namespace blender {
52
59 PyObject_HEAD
62};
63
64/* so operators called can spawn threads which acquire the GIL */
65#define BPY_RELEASE_GIL
66
70static const char *opname_as_py(const char *opname, char opname_buf[OP_MAX_TYPENAME])
71{
72 WM_operator_py_idname(opname_buf, opname);
73 return opname_buf;
74}
75
76/* -------------------------------------------------------------------- */
79
85{
86 Main *bmain = CTX_data_main(C);
87 ViewLayer *view_layer = CTX_data_view_layer(C);
88
90
91 /* None in background mode. */
92 if (view_layer) {
93 /* Update the active view layer. */
94 Scene *scene = CTX_data_scene(C);
95 Depsgraph *depsgraph = BKE_scene_ensure_depsgraph(bmain, scene, view_layer);
96 if (depsgraph && !DEG_is_evaluating(depsgraph)) {
97 DEG_make_active(depsgraph);
98 BKE_scene_graph_update_tagged(depsgraph, bmain);
99 }
100 }
101 else {
102 /* No active view layer: update all view layers in all scenes. */
103 for (Scene &scene_iter : bmain->scenes) {
104 for (ViewLayer &vl : scene_iter.view_layers) {
105 Depsgraph *depsgraph = BKE_scene_ensure_depsgraph(bmain, &scene_iter, &vl);
106 if (depsgraph && !DEG_is_evaluating(depsgraph)) {
107 DEG_make_active(depsgraph);
108 BKE_scene_graph_update_tagged(depsgraph, bmain);
109 }
110 }
111 }
112 }
113}
114
115static bool bpy_op_parse_args(PyObject *args, const char **r_context_str, bool *r_is_undo)
116{
117 const char *C_exec = "EXEC_DEFAULT";
118 bool C_undo = false;
119 bool is_exec = false;
120 bool is_undo_set = false;
121
122 Py_ssize_t args_len = PyTuple_GET_SIZE(args);
123 for (Py_ssize_t i = 0; i < args_len; i++) {
124 PyObject *arg = PyTuple_GET_ITEM(args, i);
125
126 if (!is_exec && PyUnicode_Check(arg)) {
127 if (is_undo_set) {
128 PyErr_SetString(PyExc_ValueError, "string arg must come before the boolean");
129 return false;
130 }
131 C_exec = PyUnicode_AsUTF8(arg);
132 is_exec = true;
133 }
134 else if ((r_is_undo != nullptr) && (!is_undo_set && (PyBool_Check(arg) || PyLong_Check(arg))))
135 {
136 C_undo = PyObject_IsTrue(arg);
137 is_undo_set = true;
138 }
139 else {
140 PyErr_SetString(PyExc_ValueError, "1-2 args execution context is supported");
141 return false;
142 }
143 }
144
145 *r_context_str = C_exec;
146 if (r_is_undo) {
147 *r_is_undo = C_undo;
148 }
149 return true;
150}
151
153
154/* -------------------------------------------------------------------- */
157
158static PyObject *bpy_op_fn_poll_impl(const char *opname, const char *context_str)
159{
160 char opname_buf[OP_MAX_TYPENAME];
162
163 /* XXX TODO: work out a better solution for passing on context,
164 * could make a tuple from self and pack the name and Context into it. */
166
167 if (C == nullptr) {
168 PyErr_SetString(PyExc_RuntimeError, "Context is None, cannot poll any operators");
169 return nullptr;
170 }
171
172 wmOperatorType *ot = WM_operatortype_find(opname, true);
173
174 if (ot == nullptr) {
175 PyErr_Format(PyExc_AttributeError,
176 "Polling operator \"bpy.ops.%s\" error, "
177 "could not be found",
178 opname_as_py(opname, opname_buf));
179 return nullptr;
180 }
181
182 if (context_str) {
183 int context_int = int(context);
184
185 if (RNA_enum_value_from_id(rna_enum_operator_context_items, context_str, &context_int) == 0) {
187 PyErr_Format(PyExc_TypeError,
188 "Calling operator \"bpy.ops.%s.poll\" error, "
189 "expected a string enum in (%s)",
190 opname_as_py(opname, opname_buf),
191 enum_str);
192 MEM_delete(enum_str);
193 return nullptr;
194 }
195 /* Copy back to the properly typed enum. */
196 context = wm::OpCallContext(context_int);
197 }
198
199 /* main purpose of this function */
200 PyObject *ret = WM_operator_poll_context(C, ot, context) ? Py_True : Py_False;
201
202 return Py_NewRef(ret);
203}
204
206 /* Wrap. */
207 bpy_op_fn_poll_doc,
208 ".. method:: poll(context='EXEC_DEFAULT', /)\n"
209 "\n"
210 "Test if the operator can be executed in the current context.\n"
211 "\n"
212 ":param context: Execution context (optional)\n"
213 ":type context: str\n"
214 ":return: True if the operator can be executed\n"
215 ":rtype: bool\n");
216static PyObject *bpy_op_fn_poll(BPyOpFunction *self, PyObject *args)
217{
218 const char *context_str;
219 if (!bpy_op_parse_args(args, &context_str, nullptr)) {
220 return nullptr;
221 }
222
223 return bpy_op_fn_poll_impl(self->idname, context_str);
224}
225
227
228/* -------------------------------------------------------------------- */
231
232static std::optional<wmOperatorStatus> bpy_op_fn_call_impl(const char *opname,
233 PyObject *kw,
234 const char *context_str,
235 bool is_undo)
236{
237 char opname_buf[OP_MAX_TYPENAME];
238 wmOperatorType *ot;
239 int error_val = 0;
241
243
244 /* XXX TODO: work out a better solution for passing on context,
245 * could make a tuple from self and pack the name and Context into it. */
247
248 if (C == nullptr) {
249 PyErr_SetString(PyExc_RuntimeError, "Context is None, cannot poll any operators");
250 return std::nullopt;
251 }
252
253 ot = WM_operatortype_find(opname, true);
254
255 if (ot == nullptr) {
256 PyErr_Format(PyExc_AttributeError,
257 "Calling operator \"bpy.ops.%s\" error, "
258 "could not be found",
259 opname_as_py(opname, opname_buf));
260 return std::nullopt;
261 }
262
263 if (!pyrna_write_check()) {
264 PyErr_Format(PyExc_RuntimeError,
265 "Calling operator \"bpy.ops.%s\" error, "
266 "cannot modify blend data in this state (drawing/rendering)",
267 opname_as_py(opname, opname_buf));
268 return std::nullopt;
269 }
270
271 if (context_str) {
272 int context_int = int(context);
273
274 if (RNA_enum_value_from_id(rna_enum_operator_context_items, context_str, &context_int) == 0) {
276 PyErr_Format(PyExc_TypeError,
277 "Calling operator \"bpy.ops.%s\" error, "
278 "expected a string enum in (%s)",
279 opname_as_py(opname, opname_buf),
280 enum_str);
281 MEM_delete(enum_str);
282 return std::nullopt;
283 }
284 /* Copy back to the properly typed enum. */
285 context = wm::OpCallContext(context_int);
286 }
287
288 if (WM_operator_poll_context(C, ot, context) == false) {
289 bool msg_free = false;
290 const char *msg = CTX_wm_operator_poll_msg_get(C, &msg_free);
291 PyErr_Format(PyExc_RuntimeError,
292 "Operator bpy.ops.%.200s.poll() %.200s",
293 opname_as_py(opname, opname_buf),
294 msg ? msg : "failed, context is incorrect");
296 if (msg_free) {
297 MEM_delete(msg);
298 }
299 error_val = -1;
300 }
301 else {
304
305 if (kw && PyDict_Size(kw)) {
306 error_val = pyrna_pydict_to_props(
307 &ptr, kw, false, "Converting py args to operator properties:");
308 }
309
310 if (error_val == 0) {
311 ReportList *reports;
312
313 reports = MEM_new<ReportList>("wmOperatorReportList");
314
315 /* Own so these don't move into global reports. */
317
318#ifdef BPY_RELEASE_GIL
319 /* release GIL, since a thread could be started from an operator
320 * that updates a driver */
321 /* NOTE: I have not seen any examples of code that does this
322 * so it may not be officially supported but seems to work ok. */
323 {
324 PyThreadState *ts = PyEval_SaveThread();
325#endif
326
327 retval = WM_operator_call_py(C, ot, context, &ptr, reports, is_undo);
328
329#ifdef BPY_RELEASE_GIL
330 /* regain GIL */
331 PyEval_RestoreThread(ts);
332 }
333#endif
334
335 error_val = BPy_reports_to_error(reports, PyExc_RuntimeError, false);
336
337 /* operator output is nice to have in the terminal/console too */
338 if (!reports->list.is_empty()) {
339 /* Restore the print level as this is owned by the operator now. */
340 eReportType level = eReportType(reports->printlevel);
342 BPy_reports_write_stdout(reports, nullptr);
343 BKE_report_print_level_set(reports, level);
344 }
345
346 BKE_reports_clear(reports);
347 if ((reports->flag & RPT_FREE) == 0) {
348 BKE_reports_free(reports);
349 MEM_delete(reports);
350 }
351 else {
352 /* The WM is now responsible for running the modal operator,
353 * show reports in the info window. */
354 reports->flag &= ~RPT_OP_HOLD;
355 }
356 }
357
359
360#if 0
361 /* if there is some way to know an operator takes args we should use this */
362 {
363 /* no props */
364 if (kw != nullptr) {
365 PyErr_Format(PyExc_AttributeError, "Operator \"%s\" does not take any args", opname);
366 return std::nullopt;
367 }
368
369 WM_operator_name_call(C, opname, wm::OpCallContext::ExecDefault, nullptr, nullptr);
370 }
371#endif
372 }
373
374 if (error_val == -1) {
375 return std::nullopt;
376 }
377
378 /* When calling `bpy.ops.wm.read_factory_settings()` `bpy.data's` main pointer
379 * is freed by clear_globals(), further access will crash blender.
380 * Setting context is not needed in this case, only calling because this
381 * function corrects bpy.data (internal Main pointer) */
383
384 return retval;
385}
386
387static PyObject *bpy_op_fn_call(BPyOpFunction *self, PyObject *args, PyObject *kwargs)
388{
390 if (C == nullptr) [[unlikely]] {
391 PyErr_SetString(PyExc_RuntimeError, "Context is None, cannot call an operator");
392 return nullptr;
393 }
394
395 /* Validate keyword argument keys are strings, since Python's `tp_call`
396 * does not enforce this (unlike regular Python function calls). */
397 if (kwargs && !PyC_Dict_CheckKeysAreStrings(kwargs)) {
398 PyErr_SetString(PyExc_TypeError, "keywords must be strings");
399 return nullptr;
400 }
401
402 /* Store the window manager before operator execution to check if it changes. */
404
405 /* Parse the user's positional args (context string, undo boolean)
406 * before forwarding to `bpy_op_fn_call_impl` which expects strict types. */
407 const char *context_str;
408 bool is_undo;
409 if (!bpy_op_parse_args(args, &context_str, &is_undo)) {
410 return nullptr;
411 }
412
413 /* Pre-call view-layer update.
414 *
415 * Run to account for any RNA values the user changes.
416 * NOTE: We only update active view-layer, since that's what
417 * operators are supposed to operate on. There might be some
418 * corner cases when operator need a full scene update though. */
420
421 std::optional<wmOperatorStatus> result = bpy_op_fn_call_impl(
422 self->idname, kwargs, context_str, is_undo);
423
424 if (!result) {
425 return nullptr;
426 }
427
428 /* Post-call: if operator finished and window manager unchanged, update view-layer again. */
429 if ((*result & OPERATOR_FINISHED) && CTX_wm_manager(C) == wm) {
431 }
432
433 /* Return `retval` flag as a set. */
435}
436
438
439/* -------------------------------------------------------------------- */
442
443static PyObject *bpy_op_fn_as_string_impl(const char *opname,
444 PyObject *kw,
445 bool all_args,
446 bool macro_args)
447{
448 wmOperatorType *ot;
449 int error_val = 0;
450
452
453 if (C == nullptr) {
454 PyErr_SetString(PyExc_RuntimeError,
455 "Context is None, cannot get the string representation of this object.");
456 return nullptr;
457 }
458
459 ot = WM_operatortype_find(opname, true);
460
461 if (ot == nullptr) {
462 PyErr_Format(PyExc_AttributeError,
463 "_bpy.ops.as_string: operator \"%.200s\" "
464 "could not be found",
465 opname);
466 return nullptr;
467 }
468
469 // ptr = WM_operator_properties_create(opname);
470 /* Save another lookup */
471 PointerRNA ptr = RNA_pointer_create_discrete(nullptr, ot->srna, nullptr);
472
473 if (kw && PyDict_Size(kw)) {
474 error_val = pyrna_pydict_to_props(
475 &ptr, kw, false, "Converting py args to operator properties:");
476 }
477
478 std::string op_string;
479 if (error_val == 0) {
480 op_string = WM_operator_pystring_ex(C, nullptr, all_args, macro_args, ot, &ptr);
481 }
482
484
485 if (error_val == -1) {
486 return nullptr;
487 }
488
489 return PyC_UnicodeFromStdStr(op_string);
490}
491
492static PyObject *bpy_op_fn_as_string(BPyOpFunction *self)
493{
494 return bpy_op_fn_as_string_impl(self->idname, nullptr, true, true);
495}
496
498
499/* -------------------------------------------------------------------- */
502
503static PyObject *bpy_op_fn_get_rna_type_impl(const char *opname)
504{
505 wmOperatorType *ot = WM_operatortype_find(opname, true);
506 if (ot == nullptr) {
507 PyErr_Format(PyExc_KeyError, "get_rna_type(\"%s\") not found", opname);
508 return nullptr;
509 }
510
511 PointerRNA ptr = RNA_pointer_create_discrete(nullptr, RNA_Struct, ot->srna);
512 BPy_StructRNA *pyrna = reinterpret_cast<BPy_StructRNA *>(pyrna_struct_CreatePyObject(&ptr));
513 return reinterpret_cast<PyObject *>(pyrna);
514}
515
517 /* Wrap. */
518 bpy_op_fn_get_rna_type_doc,
519 ".. method:: get_rna_type()\n"
520 "\n"
521 "Get the RNA type definition for this operator.\n"
522 "\n"
523 ":return: RNA type object for introspection\n"
524 ":rtype: :class:`bpy.types.Struct`\n");
525static PyObject *bpy_op_fn_get_rna_type(BPyOpFunction *self, PyObject * /*args*/)
526{
528}
529
530PyObject *pyop_getrna_type(PyObject * /*self*/, PyObject *value)
531{
532 const char *opname = PyUnicode_AsUTF8(value);
533 if (opname == nullptr) {
534 PyErr_Format(PyExc_TypeError, "get_rna_type() expects a string argument");
535 return nullptr;
536 }
537 return bpy_op_fn_get_rna_type_impl(opname);
538}
539
541
542/* -------------------------------------------------------------------- */
545
546static PyObject *bpy_op_fn_get_bl_options_impl(const char *opname)
547{
548 wmOperatorType *ot = WM_operatortype_find(opname, true);
549 if (ot == nullptr) {
550 PyErr_Format(PyExc_KeyError, "get_bl_options(\"%s\") not found", opname);
551 return nullptr;
552 }
554}
555
557 /* Wrap. */
558 bpy_op_fn_get_bl_options_doc,
559 "Set of option flags for this operator (e.g. 'REGISTER', 'UNDO').\n"
560 "\n"
561 ":type: set[str]\n");
562static PyObject *bpy_op_fn_get_bl_options(BPyOpFunction *self, void * /*closure*/)
563{
565}
566
568
569/* -------------------------------------------------------------------- */
572
574{
575 Py_TYPE(self)->tp_free(reinterpret_cast<PyObject *>(self));
576}
577
581static PyObject *bpy_op_fn_str(BPyOpFunction *self)
582{
583 char idname_py[OP_MAX_TYPENAME];
584 WM_operator_py_idname(idname_py, self->idname);
585
586 /* Extract module and function from idname_py. */
587 const char *dot_pos = strchr(idname_py, '.');
588 if (!dot_pos) {
589 return PyUnicode_FromFormat(
590 "<function bpy.ops.%s at %p>", idname_py, static_cast<void *>(self));
591 }
592
593 size_t op_mod_str_len = dot_pos - idname_py;
594 char op_mod_str[OP_MAX_TYPENAME];
595 char op_fn_str[OP_MAX_TYPENAME];
596
597 /* Copy with bounds checking. */
598 if (op_mod_str_len >= sizeof(op_mod_str)) {
599 /* Truncate if necessary. */
600 op_mod_str_len = sizeof(op_mod_str) - 1;
601 }
602 memcpy(op_mod_str, idname_py, op_mod_str_len);
603 op_mod_str[op_mod_str_len] = '\0';
604 STRNCPY(op_fn_str, dot_pos + 1);
605
606 return PyUnicode_FromFormat(
607 "<function bpy.ops.%s.%s at %p>", op_mod_str, op_fn_str, static_cast<void *>(self));
608}
609
613static PyObject *bpy_op_fn_repr(BPyOpFunction *self)
614{
615 /* Use the same format as the original Python implementation */
616 PyObject *result = bpy_op_fn_as_string(self);
617 if (!result) {
618 /* Fallback to simple string if bpy_op_fn_as_string fails. */
619 PyErr_Clear();
620 char idname_py[OP_MAX_TYPENAME];
621 WM_operator_py_idname(idname_py, self->idname);
622 return PyUnicode_FromFormat("<bpy.ops.%s function>", idname_py);
623 }
624
625 return result;
626}
627
629
630/* -------------------------------------------------------------------- */
633
635 /* Wrap. */
636 bpy_op_fn_idname_doc,
637 ".. method:: idname()\n"
638 "\n"
639 ":return: Return the Blender-format operator idname (e.g., 'OBJECT_OT_select_all').\n"
640 ":rtype: str\n");
641static PyObject *bpy_op_fn_idname(BPyOpFunction *self, PyObject * /*args*/)
642{
643 return PyUnicode_FromString(self->idname);
644}
645
647 /* Wrap. */
648 bpy_op_fn_idname_py_doc,
649 ".. method:: idname_py()\n"
650 "\n"
651 ":return: Return the Python-format operator idname (e.g., 'object.select_all').\n"
652 ":rtype: str\n");
653static PyObject *bpy_op_fn_idname_py(BPyOpFunction *self, PyObject * /*args*/)
654{
655 char idname_py[OP_MAX_TYPENAME];
656 WM_operator_py_idname(idname_py, self->idname);
657 return PyUnicode_FromString(idname_py);
658}
659
661{
662 /* Get operator signature using Blender format idname:
663 * `_op_as_string(self.idname())` where `idname()` returns Blender format. */
664 PyObject *sig_result = bpy_op_fn_as_string(self);
665
666 if (!sig_result) {
667 /* Fallback to simple string if `bpy_op_fn_as_string` fails. */
668 PyErr_Clear();
669 char idname_py[OP_MAX_TYPENAME];
670 WM_operator_py_idname(idname_py, self->idname);
671 return PyUnicode_FromFormat("bpy.ops.%s(...)", idname_py);
672 }
673
674 /* Get RNA type and description using Blender format idname. */
675 PyObject *rna_type = bpy_op_fn_get_rna_type(self, nullptr);
676
677 if (!rna_type) {
678 PyErr_Clear();
679 return sig_result; /* Return just signature on failure. */
680 }
681
682 /* Get description attribute from RNA type. */
683 PyObject *description = PyObject_GetAttrString(rna_type, "description");
684 Py_DECREF(rna_type);
685
686 if (!description) {
687 PyErr_Clear();
688 return sig_result; /* Return just signature on failure. */
689 }
690
691 /* Combine signature and description with newline. */
692 PyObject *combined = PyUnicode_FromFormat("%U\n%U", sig_result, description);
693 Py_DECREF(sig_result);
694 Py_DECREF(description);
695
696 if (!combined) {
697 char idname_py[OP_MAX_TYPENAME];
698 WM_operator_py_idname(idname_py, self->idname);
699 return PyUnicode_FromFormat("bpy.ops.%s(...)", idname_py);
700 }
701
702 return combined;
703}
704
706static PyMethodDef bpy_op_fn_methods[] = {
707 {"poll", reinterpret_cast<PyCFunction>(bpy_op_fn_poll), METH_VARARGS, bpy_op_fn_poll_doc},
708 {"get_rna_type",
709 reinterpret_cast<PyCFunction>(bpy_op_fn_get_rna_type),
710 METH_NOARGS,
711 bpy_op_fn_get_rna_type_doc},
712 {"idname", reinterpret_cast<PyCFunction>(bpy_op_fn_idname), METH_NOARGS, bpy_op_fn_idname_doc},
713 {"idname_py",
714 reinterpret_cast<PyCFunction>(bpy_op_fn_idname_py),
715 METH_NOARGS,
716 bpy_op_fn_idname_py_doc},
717 {nullptr, nullptr, 0, nullptr}};
718
720
721/* -------------------------------------------------------------------- */
724
725static PyObject *bpy_op_fn_get_doc(BPyOpFunction *self, void * /*closure*/)
726{
727 return bpy_op_fn_get_doc_impl(self);
728}
729
730static PyGetSetDef bpy_op_fn_getsetters[] = {
731 {"bl_options",
732 reinterpret_cast<getter>(bpy_op_fn_get_bl_options),
733 nullptr,
734 bpy_op_fn_get_bl_options_doc,
735 nullptr},
736 /* No docstring, as this is standard part of the Python spec. */
737 {"__doc__", reinterpret_cast<getter>(bpy_op_fn_get_doc), nullptr, nullptr, nullptr},
738 {nullptr, nullptr, nullptr, nullptr, nullptr}};
739
741
742/* -------------------------------------------------------------------- */
745
747 /* Wrap. */
748 bpy_op_fn_doc,
749 "BPyOpFunction(context='EXEC_DEFAULT', undo=False, **kwargs)\n"
750 "\n"
751 " Execute the operator with the given parameters.\n"
752 "\n"
753 " :param context: Execution context (optional)\n"
754 " :type context: str\n"
755 " :param undo: Force undo behavior (optional)\n"
756 " :type undo: bool\n"
757 " :param kwargs: Operator properties\n"
758 " :return: Set of completion status flags\n"
759 " :rtype: set[str]\n");
760static PyTypeObject BPyOpFunctionType = {
761 /*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
762 /*tp_name*/ "BPyOpFunction",
763 /*tp_basicsize*/ sizeof(BPyOpFunction),
764 /*tp_itemsize*/ 0,
765 /*tp_dealloc*/ reinterpret_cast<destructor>(bpy_op_fn_dealloc),
766 /*tp_print*/ 0,
767 /*tp_getattr*/ nullptr,
768 /*tp_setattr*/ nullptr,
769 /*tp_as_async*/ nullptr,
770 /*tp_repr*/ reinterpret_cast<reprfunc>(bpy_op_fn_repr),
771 /*tp_as_number*/ nullptr,
772 /*tp_as_sequence*/ nullptr,
773 /*tp_as_mapping*/ nullptr,
774 /*tp_hash*/ nullptr,
775 /*tp_call*/ reinterpret_cast<ternaryfunc>(bpy_op_fn_call),
776 /*tp_str*/ reinterpret_cast<reprfunc>(bpy_op_fn_str),
777 /*tp_getattro*/ PyObject_GenericGetAttr,
778 /*tp_setattro*/ nullptr,
779 /*tp_as_buffer*/ nullptr,
780 /*tp_flags*/ Py_TPFLAGS_DEFAULT,
781 /*tp_doc*/ bpy_op_fn_doc,
782 /*tp_traverse*/ nullptr,
783 /*tp_clear*/ nullptr,
784 /*tp_richcompare*/ nullptr,
785 /*tp_weaklistoffset*/ 0,
786 /*tp_iter*/ nullptr,
787 /*tp_iternext*/ nullptr,
788 /*tp_methods*/ bpy_op_fn_methods,
789 /*tp_members*/ nullptr,
790 /*tp_getset*/ bpy_op_fn_getsetters,
791 /*tp_base*/ nullptr,
792 /*tp_dict*/ nullptr,
793 /*tp_descr_get*/ nullptr,
794 /*tp_descr_set*/ nullptr,
795 /*tp_dictoffset*/ 0,
796 /*tp_init*/ nullptr,
797 /*tp_alloc*/ nullptr,
798 /*tp_new*/ nullptr,
799 /*tp_free*/ nullptr,
800 /*tp_is_gc*/ nullptr,
801 /*tp_bases*/ nullptr,
802 /*tp_mro*/ nullptr,
803 /*tp_cache*/ nullptr,
804 /*tp_subclasses*/ nullptr,
805 /*tp_weaklist*/ nullptr,
806 /*tp_del*/ nullptr,
807 /*tp_version_tag*/ 0,
808 /*tp_finalize*/ nullptr,
809 /*tp_vectorcall*/ nullptr,
810};
811
813
814/* -------------------------------------------------------------------- */
817
819{
820 if (PyType_Ready(&BPyOpFunctionType) < 0) {
821 return -1;
822 }
823 return 0;
824}
825
826PyObject *pyop_create_function(PyObject * /*self*/, PyObject *args)
827{
828 const char *op_mod_str, *op_fn_str;
829
830 if (!PyArg_ParseTuple(args,
831 "s" /* `module` */
832 "s" /* `operator` */
833 ":create_function",
834 &op_mod_str,
835 &op_fn_str))
836 {
837 return nullptr;
838 }
839
840 /* Validate operator name lengths before constructing strings. */
841 size_t bl_len = strlen(op_mod_str) + 4 + strlen(op_fn_str) + 1; /* "_OT_" + null terminator */
842 if (bl_len > OP_MAX_TYPENAME) {
843 PyErr_Format(PyExc_ValueError, "Operator name too long: %s.%s", op_mod_str, op_fn_str);
844 return nullptr;
845 }
846
847 /* Create a new #BPyOpFunction instance for direct operator execution. */
848 BPyOpFunction *op_fn = static_cast<BPyOpFunction *> PyObject_New(BPyOpFunction,
850 if (!op_fn) {
851 return nullptr;
852 }
853
854 /* Construct the Blender `idname` (e.g., `OBJECT_OT_select_all`). */
855 char op_mod_str_upper[OP_MAX_TYPENAME];
856 STRNCPY(op_mod_str_upper, op_mod_str);
857 BLI_str_toupper_ascii(op_mod_str_upper, sizeof(op_mod_str_upper));
858
859 const size_t idname_len = SNPRINTF(op_fn->idname, "%s_OT_%s", op_mod_str_upper, op_fn_str);
860 /* Prevented by the #OP_MAX_TYPENAME check. */
861 BLI_assert(idname_len < sizeof(op_fn->idname));
862 UNUSED_VARS_NDEBUG(idname_len);
863 return reinterpret_cast<PyObject *>(op_fn);
864}
865
867
868} // namespace blender
#define SNPRINTF(dst, format,...)
bool CLG_quiet_get()
Definition clog.cc:942
#define OP_MAX_TYPENAME
Read Blender memory allocation and freeing.
#define C
Definition RandGen.cpp:29
#define UNUSED_VARS_NDEBUG(...)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static PyObject * bpy_op_fn_get_doc(BPyOpFunction *self, void *)
static const char * opname_as_py(const char *opname, char opname_buf[OP_MAX_TYPENAME])
char * STRNCPY(char(&dst)[N], const char *src)
@ RPT_WARNING
Definition BKE_report.hh:40
void BLI_str_toupper_ascii(char *str, size_t len) ATTR_NONNULL(1)
static PyObject * bpy_op_fn_get_bl_options_impl(const char *opname)
void BPY_modules_update()
void WM_operator_properties_sanitize(PointerRNA *ptr, const bool no_context)
void BKE_reports_free(ReportList *reports)
Definition report.cc:106
void BKE_report_print_level_set(ReportList *reports, eReportType level)
Definition report.cc:276
void WM_operator_properties_free(PointerRNA *ptr)
void BKE_reports_init(ReportList *reports, int flag)
Definition report.cc:91
void BPy_reports_write_stdout(const ReportList *reports, const char *header)
int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const bool all_args, const char *error_prefix)
Definition bpy_rna.cc:1618
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
PointerRNA WM_operator_properties_create_ptr(wmOperatorType *ot)
static PyObject * bpy_op_fn_as_string(BPyOpFunction *self)
static PyGetSetDef bpy_op_fn_getsetters[]
void BKE_reports_clear(ReportList *reports)
Definition report.cc:118
void DEG_make_active(Depsgraph *depsgraph)
Definition depsgraph.cc:337
static PyObject * bpy_op_fn_repr(BPyOpFunction *self)
PyObject * pyrna_struct_CreatePyObject(PointerRNA *ptr)
Definition bpy_rna.cc:8874
ViewLayer * CTX_data_view_layer(const bContext *C)
static PyObject * bpy_op_fn_get_rna_type_impl(const char *opname)
bool RNA_enum_value_from_id(const EnumPropertyItem *item, const char *identifier, int *r_value)
const EnumPropertyItem rna_enum_operator_return_items[]
Definition rna_wm.cc:595
wmOperatorStatus WM_operator_call_py(bContext *C, wmOperatorType *ot, wm::OpCallContext context, PointerRNA *properties, ReportList *reports, const bool is_undo)
std::string WM_operator_pystring_ex(bContext *C, wmOperator *op, const bool all_args, const bool macro_args, wmOperatorType *ot, PointerRNA *opptr)
bool PyC_Dict_CheckKeysAreStrings(PyObject *dict)
struct bContext * BPY_context_get()
const EnumPropertyItem rna_enum_operator_context_items[]
Definition rna_ui.cc:36
wmWindowManager * CTX_wm_manager(const bContext *C)
static PyObject * bpy_op_fn_as_string_impl(const char *opname, PyObject *kw, bool all_args, bool macro_args)
static void bpy_op_fn_dealloc(BPyOpFunction *self)
PyObject * pyop_create_function(PyObject *, PyObject *args)
bool BKE_main_view_layers_synced_ensure(const Main *bmain)
void BKE_scene_graph_update_tagged(Depsgraph *depsgraph, Main *bmain)
Definition scene.cc:2867
PointerRNA RNA_pointer_create_discrete(ID *id, StructRNA *type, void *data)
int BPyOpFunction_InitTypes()
const char * CTX_wm_operator_poll_msg_get(bContext *C, bool *r_free)
bool WM_operator_poll_context(bContext *C, wmOperatorType *ot, wm::OpCallContext context)
wmOperatorStatus WM_operator_name_call(bContext *C, const char *opstring, wm::OpCallContext context, PointerRNA *properties, const wmEvent *event)
static PyObject * bpy_op_fn_idname_py(BPyOpFunction *self, PyObject *)
static PyObject * bpy_op_fn_call(BPyOpFunction *self, PyObject *args, PyObject *kwargs)
static void bpy_op_view_layer_update(bContext *C)
static PyTypeObject BPyOpFunctionType
static PyObject * bpy_op_fn_idname(BPyOpFunction *self, PyObject *)
wmOperatorType * WM_operatortype_find(const char *idname, bool quiet)
PyObject * pyrna_enum_bitfield_as_set(const EnumPropertyItem *items, int value)
static PyObject * bpy_op_fn_get_bl_options(BPyOpFunction *self, void *)
PyObject * pyop_getrna_type(PyObject *, PyObject *value)
Main * CTX_data_main(const bContext *C)
static PyObject * bpy_op_fn_poll(BPyOpFunction *self, PyObject *args)
bool pyrna_write_check()
Definition bpy_rna.cc:515
const EnumPropertyItem rna_enum_operator_type_flag_items[]
Definition rna_wm.cc:550
static bool bpy_op_parse_args(PyObject *args, const char **r_context_str, bool *r_is_undo)
PyObject * PyC_UnicodeFromStdStr(const std::string &str)
static PyObject * bpy_op_fn_get_rna_type(BPyOpFunction *self, PyObject *)
Scene * CTX_data_scene(const bContext *C)
Depsgraph * BKE_scene_ensure_depsgraph(Main *bmain, Scene *scene, ViewLayer *view_layer)
Definition scene.cc:3644
short BPy_reports_to_error(ReportList *reports, PyObject *exception, const bool clear)
static PyObject * bpy_op_fn_poll_impl(const char *opname, const char *context_str)
@ RPT_OP_HOLD
Definition BKE_report.hh:60
@ RPT_PRINT_HANDLED_BY_OWNER
Definition BKE_report.hh:62
char * pyrna_enum_repr(const EnumPropertyItem *item)
static PyObject * bpy_op_fn_str(BPyOpFunction *self)
static PyMethodDef bpy_op_fn_methods[]
static std::optional< wmOperatorStatus > bpy_op_fn_call_impl(const char *opname, PyObject *kw, const char *context_str, bool is_undo)
bool DEG_is_evaluating(const Depsgraph *depsgraph)
Definition depsgraph.cc:318
size_t WM_operator_py_idname(char *dst, const char *src)
void CTX_wm_operator_poll_msg_clear(bContext *C)
static PyObject * bpy_op_fn_get_doc_impl(BPyOpFunction *self)
header-only compatibility defines.
PyObject_HEAD char idname[OP_MAX_TYPENAME]
ListBaseT< Scene > scenes
Definition BKE_main.hh:386
ListBaseT< Report > list
Definition BKE_report.hh:79
ListBaseT< ViewLayer > view_layers