Blender V4.5
bpy_interface.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
12
13#include <Python.h>
14#include <frameobject.h>
15
16#ifdef WITH_PYTHON_MODULE
17# include "pylifecycle.h" /* For `Py_Version`. */
18#endif
19#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
20
21#include "CLG_log.h"
22
23#include "BLI_listbase.h"
24#include "BLI_path_utils.hh"
25#include "BLI_string.h"
26#include "BLI_threads.h"
27#include "BLI_utildefines.h"
28
29#include "BLT_translation.hh"
30
31#include "RNA_types.hh"
32
33#include "bpy.hh"
34#include "bpy_capi_utils.hh"
35#include "bpy_intern_string.hh"
36#include "bpy_path.hh"
37#include "bpy_props.hh"
38#include "bpy_rna.hh"
39
41
42#include "DNA_freestyle_types.h"
43#include "DNA_layer_types.h"
44#include "DNA_scene_types.h"
45#include "DNA_text_types.h"
46
47#include "BKE_appdir.hh"
48#include "BKE_context.hh"
49#include "BKE_global.hh" /* Only for script checking. */
50#include "BKE_main.hh"
51#include "BKE_text.h"
52
53#ifdef WITH_CYCLES
54# include "CCL_api.h"
55#endif
56
57#include "BPY_extern.hh"
58#include "BPY_extern_python.hh"
59#include "BPY_extern_run.hh"
60
62
63/* `inittab` initialization functions. */
65#include "../generic/bgl.hh"
70#include "../gpu/gpu_py_api.hh"
72
73/* Logging types to use anywhere in the Python modules. */
74
78
79/* For internal use, when starting and ending Python scripts. */
80
81/* In case a Python script triggers another Python call,
82 * stop #bpy_context_clear from invalidating. */
83static int py_call_level = 0;
84
85/* Set by command line arguments before Python starts. */
86static bool py_use_system_env = false;
87
88// #define TIME_PY_RUN /* Simple python tests. prints on exit. */
89
90#ifdef TIME_PY_RUN
91# include "BLI_time.h"
92static int bpy_timer_count = 0;
94static double bpy_timer;
96static double bpy_timer_run;
98static double bpy_timer_run_tot;
99#endif
100
102{
103 /* Don't do this from a non-main (e.g. render) thread, it can cause a race
104 * condition on `C->data.recursion`. Ideal solution would be to disable
105 * context entirely from non-main threads, but that's more complicated. */
106 if (!BLI_thread_is_main()) {
107 return;
108 }
109
111
112 /* Can give really bad results if this isn't here. */
114}
115
116void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
117{
119
120 if (gilstate) {
121 *gilstate = PyGILState_Ensure();
122 }
123
124 if (py_call_level == 1) {
126
127#ifdef TIME_PY_RUN
128 if (bpy_timer_count == 0) {
129 /* Record time from the beginning. */
130 bpy_timer = BLI_time_now_seconds();
131 bpy_timer_run = bpy_timer_run_tot = 0.0;
132 }
133 bpy_timer_run = BLI_time_now_seconds();
134
135 bpy_timer_count++;
136#endif
137 }
138}
139
140void bpy_context_clear(bContext * /*C*/, const PyGILState_STATE *gilstate)
141{
143
144 if (gilstate) {
145 PyGILState_Release(*gilstate);
146 }
147
148 if (py_call_level < 0) {
149 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
150 }
151 else if (py_call_level == 0) {
152 /* NOTE: Unfortunately calling classes currently won't store the context.
153 * Can't set nullptr because of this - but this is very unreliable still. */
154#if 0
155 BPY_context_set(nullptr);
156#endif
157
158#ifdef TIME_PY_RUN
159 bpy_timer_run_tot += BLI_time_now_seconds() - bpy_timer_run;
160 bpy_timer_count++;
161#endif
162 }
163}
164
166{
167 if (UNLIKELY(C == nullptr)) {
168 return;
169 }
171}
172
174 void *dict_orig,
175 const char *context_members[],
176 uint context_members_len)
177{
178 PyGILState_STATE gilstate;
179 const bool use_gil = !PyC_IsInterpreterActive();
180 if (use_gil) {
181 gilstate = PyGILState_Ensure();
182 }
183
184 /* Copy on write. */
185 if (*dict_p == dict_orig) {
186 *dict_p = PyDict_Copy(static_cast<PyObject *>(dict_orig));
187 }
188
189 PyObject *dict = static_cast<PyObject *>(*dict_p);
190 BLI_assert(PyDict_Check(dict));
191
192 /* Use #PyDict_Pop instead of #PyDict_DelItemString to avoid setting the exception,
193 * while supported it's good to avoid for low level functions like this that run often. */
194 for (uint i = 0; i < context_members_len; i++) {
195 PyObject *key = PyUnicode_FromString(context_members[i]);
196 PyObject *item = _PyDict_Pop(dict, key, Py_None);
197 Py_DECREF(key);
198 Py_DECREF(item);
199 }
200
201 if (use_gil) {
202 PyGILState_Release(gilstate);
203 }
204}
205
207{
208 if (text->compiled) {
209 PyGILState_STATE gilstate;
210 const bool use_gil = !PyC_IsInterpreterActive();
211
212 if (use_gil) {
213 gilstate = PyGILState_Ensure();
214 }
215
216 Py_DECREF((PyObject *)text->compiled);
217 text->compiled = nullptr;
218
219 if (use_gil) {
220 PyGILState_Release(gilstate);
221 }
222 }
223}
224
226{
227 /* Correct but slow, this runs all the time operator poll, panel draw etc
228 * (100's of time a second). */
229#if 0
230 PyObject *mod = PyImport_ImportModuleLevel("bpy", nullptr, nullptr, nullptr, 0);
231 PyModule_AddObject(mod, "data", BPY_rna_module());
232 PyModule_AddObject(mod, "types", BPY_rna_types()); /* This does not need updating. */
233#endif
234
235 /* Refreshes the main struct. */
237}
238
240{
241 return static_cast<bContext *>(bpy_context_module->ptr->data);
242}
243
245{
246 bpy_context_module->ptr->data = (void *)C;
247}
248
249#ifdef WITH_FLUID
250/* Defined in `manta` module. */
251extern "C" PyObject *Manta_initPython();
252#endif
253
254#ifdef WITH_AUDASPACE_PY
255/* Defined in `AUD_C-API.cpp`. */
256extern "C" PyObject *AUD_initPython();
257#endif
258
259#ifdef WITH_CYCLES
260/* Defined in `cycles` module. */
261static PyObject *CCL_initPython()
262{
263 return (PyObject *)CCL_python_module_init();
264}
265#endif
266
267#ifdef WITH_HYDRA
268/* Defined in `render_hydra` module. */
269PyObject *BPyInit_hydra();
270#endif
271
272static _inittab bpy_internal_modules[] = {
273 {"mathutils", PyInit_mathutils},
274#if 0
275 {"mathutils.geometry", PyInit_mathutils_geometry},
276 {"mathutils.noise", PyInit_mathutils_noise},
277 {"mathutils.kdtree", PyInit_mathutils_kdtree},
278#endif
279 {"_bpy_path", BPyInit__bpy_path},
280 {"bgl", BPyInit_bgl},
281 {"blf", BPyInit_blf},
282 {"bl_math", BPyInit_bl_math},
283 {"imbuf", BPyInit_imbuf},
284 {"bmesh", BPyInit_bmesh},
285#if 0
286 {"bmesh.types", BPyInit_bmesh_types},
287 {"bmesh.utils", BPyInit_bmesh_utils},
288 {"bmesh.utils", BPyInit_bmesh_geometry},
289#endif
290#ifdef WITH_FLUID
291 {"manta", Manta_initPython},
292#endif
293#ifdef WITH_AUDASPACE_PY
294 {"aud", AUD_initPython},
295#endif
296#ifdef WITH_CYCLES
297 {"_cycles", CCL_initPython},
298#endif
299 {"gpu", BPyInit_gpu},
300 {"idprop", BPyInit_idprop},
301#ifdef WITH_HYDRA
302 {"_bpy_hydra", BPyInit_hydra},
303#endif
304 {nullptr, nullptr},
305};
306
307#ifndef WITH_PYTHON_MODULE
317static void pystatus_exit_on_error(const PyStatus &status)
318{
319 if (UNLIKELY(PyStatus_Exception(status))) {
320 fputs("Internal error initializing Python!\n", stderr);
321 /* This calls `exit`. */
322 Py_ExitStatusException(status);
323 }
324}
325#endif
326
327void BPY_python_start(bContext *C, int argc, const char **argv)
328{
329#ifndef WITH_PYTHON_MODULE
330 BLI_assert_msg(Py_IsInitialized() == 0, "Python has already been initialized");
331
332 /* #PyPreConfig (early-configuration). */
333 {
334 PyPreConfig preconfig;
335 PyStatus status;
336
337 /* To narrow down reports where the systems Python is inexplicably used, see: #98131. */
338 CLOG_INFO(
340 2,
341 "Initializing %s support for the systems Python environment such as 'PYTHONPATH' and "
342 "the user-site directory.",
343 py_use_system_env ? "*with*" : "*without*");
344
345 if (py_use_system_env) {
346 PyPreConfig_InitPythonConfig(&preconfig);
347 }
348 else {
349 /* Only use the systems environment variables and site when explicitly requested.
350 * Since an incorrect 'PYTHONPATH' causes difficult to debug errors, see: #72807.
351 * An alternative to setting `preconfig.use_environment = 0` */
352 PyPreConfig_InitIsolatedConfig(&preconfig);
353 }
354
355 /* Force UTF8 on all platforms, since this is what's used for Blender's internal strings,
356 * providing consistent encoding behavior across all Blender installations.
357 *
358 * This also uses the `surrogateescape` error handler ensures any unexpected bytes are escaped
359 * instead of raising an error.
360 *
361 * Without this `sys.getfilesystemencoding()` and `sys.stdout` for example may be set to ASCII
362 * or some other encoding - where printing some UTF8 values will raise an error.
363 *
364 * This can cause scripts to fail entirely on some systems.
365 *
366 * This assignment is the equivalent of enabling the `PYTHONUTF8` environment variable.
367 * See `PEP-540` for details on exactly what this changes. */
368 preconfig.utf8_mode = true;
369
370 /* Note that there is no reason to call #Py_PreInitializeFromBytesArgs here
371 * as this is only used so that command line arguments can be handled by Python itself,
372 * not for setting `sys.argv` (handled below). */
373 status = Py_PreInitialize(&preconfig);
375 }
376
377 /* Must run before python initializes, but after #PyPreConfig. */
378 PyImport_ExtendInittab(bpy_internal_modules);
379
380 /* #PyConfig (initialize Python). */
381 {
382 PyConfig config;
383 PyStatus status;
384 bool has_python_executable = false;
385
386 if (py_use_system_env) {
387 PyConfig_InitPythonConfig(&config);
388
389 BLI_assert(config.install_signal_handlers);
390 }
391 else {
392 PyConfig_InitIsolatedConfig(&config);
393 /* Python's isolated config disables its own signal overrides.
394 * While it makes sense not to interfering with other components of the process,
395 * the signal handlers are needed for Python's own error handling to work properly.
396 * Without this a `SIGPIPE` signal will crash Blender, see: #129657. */
397 config.install_signal_handlers = 1;
398 }
399
400 /* Suppress error messages when calculating the module search path.
401 * While harmless, it's noisy. */
402 config.pathconfig_warnings = 0;
403
404 /* Allow the user site directory because this is used
405 * when PIP installing packages from Blender, see: #104000.
406 *
407 * NOTE(@ideasman42): While an argument can be made for isolating Blender's Python
408 * from the users home directory entirely, an alternative directory should be used in that
409 * case - so PIP can be used to install packages. Otherwise PIP will install packages to a
410 * directory which us not in the users `sys.path`, see `site.USER_BASE` for details. */
411 // config.user_site_directory = py_use_system_env;
412
413 /* While `sys.argv` is set, we don't want Python to interpret it. */
414 config.parse_argv = 0;
415 status = PyConfig_SetBytesArgv(&config, argc, (char *const *)argv);
417
418 /* Needed for Python's initialization for portable Python installations.
419 * We could use #Py_SetPath, but this overrides Python's internal logic
420 * for calculating its own module search paths.
421 *
422 * `sys.executable` is overwritten after initialization to the Python binary. */
423 {
424 const char *program_path = BKE_appdir_program_path();
425 status = PyConfig_SetBytesString(&config, &config.program_name, program_path);
427 }
428
429 /* Setting the program name is important so the 'multiprocessing' module
430 * can launch new Python instances. */
431 {
432 char program_path[FILE_MAX];
434 program_path, sizeof(program_path), PY_MAJOR_VERSION, PY_MINOR_VERSION))
435 {
436 status = PyConfig_SetBytesString(&config, &config.executable, program_path);
438 has_python_executable = true;
439 }
440 else {
441 /* Set to `sys.executable = None` below (we can't do before Python is initialized). */
442 fprintf(stderr,
443 "Unable to find the Python binary, "
444 "the multiprocessing module may not be functional!\n");
445 }
446 }
447
448 /* Allow to use our own included Python. `py_path_bundle` may be nullptr. */
449 {
450 const std::optional<std::string> py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON,
451 nullptr);
452 if (py_path_bundle.has_value()) {
453
454# ifdef __APPLE__
455 /* Mac-OS allows file/directory names to contain `:` character
456 * (represented as `/` in the Finder) but current Python lib (as of release 3.1.1)
457 * doesn't handle these correctly. */
458 if (strchr(py_path_bundle->c_str(), ':')) {
459 fprintf(stderr,
460 "Warning! Blender application is located in a path containing ':' or '/' chars\n"
461 "This may make Python import function fail\n");
462 }
463# endif /* __APPLE__ */
464
465 status = PyConfig_SetBytesString(&config, &config.home, py_path_bundle->c_str());
467
468# ifdef PYTHON_SSL_CERT_FILE
469 /* Point to the portable SSL certificate to support HTTPS access, see: #102300. */
470 const char *ssl_cert_file_env = "SSL_CERT_FILE";
471 if (BLI_getenv(ssl_cert_file_env) == nullptr) {
472 const char *ssl_cert_file_suffix = PYTHON_SSL_CERT_FILE;
473 char ssl_cert_file[FILE_MAX];
475 ssl_cert_file, sizeof(ssl_cert_file), py_path_bundle->c_str(), ssl_cert_file_suffix);
476 BLI_setenv(ssl_cert_file_env, ssl_cert_file);
477 }
478# endif /* PYTHON_SSL_CERT_FILE */
479 }
480 else {
481/* Common enough to use the system Python on Linux/Unix, warn on other systems. */
482# if defined(__APPLE__) || defined(_WIN32)
483 fprintf(stderr,
484 "Bundled Python not found and is expected on this platform "
485 "(the 'install' target may have not been built)\n");
486# endif
487 }
488 }
489
490 /* Initialize Python (also acquires lock). */
491 status = Py_InitializeFromConfig(&config);
492 PyConfig_Clear(&config);
493
495
496 if (!has_python_executable) {
497 PySys_SetObject("executable", Py_None);
498 }
499 }
500
501# ifdef WITH_FLUID
502 /* Required to prevent assertion error, see:
503 * https://stackoverflow.com/questions/27844676 */
504 Py_DECREF(PyImport_ImportModule("threading"));
505# endif
506
507#else /* WITH_PYTHON_MODULE */
508 (void)argc;
509 (void)argv;
510
511 /* NOTE(ideasman42): unfortunately the `inittab` can only be used
512 * before Python has been initialized.
513 * When built as a Python module, Python will have been initialized
514 * and using the `inittab` isn't supported.
515 * So it's necessary to load all modules as soon as `bpy` is imported. */
516 // PyImport_ExtendInittab(bpy_internal_modules);
517
518#endif /* WITH_PYTHON_MODULE */
519
521
522#ifdef WITH_PYTHON_MODULE
523 {
524 /* Manually load all modules */
525 struct _inittab *inittab_item;
526 PyObject *sys_modules = PyImport_GetModuleDict();
527
528 for (inittab_item = bpy_internal_modules; inittab_item->name; inittab_item++) {
529 PyObject *mod = inittab_item->initfunc();
530 if (mod) {
531 PyDict_SetItemString(sys_modules, inittab_item->name, mod);
532 }
533 else {
534 PyErr_Print();
535 PyErr_Clear();
536 }
537 // Py_DECREF(mod); /* Ideally would decref, but in this case we never want to free. */
538 }
539 }
540#endif
541
542 /* Run first, initializes RNA types. */
543 BPY_rna_init();
544
545 /* Defines `bpy.*` and lets us import it. */
547
549
550#ifndef WITH_PYTHON_MODULE
551 /* Python module runs `atexit` when `bpy` is freed. */
552 BPY_atexit_register(); /* This can initialize any time. */
553
554 /* Free the lock acquired (implicitly) when Python is initialized. */
555 PyEval_ReleaseThread(PyGILState_GetThisThreadState());
556
557#endif
558
559#ifdef WITH_PYTHON_MODULE
560 /* Disable all add-ons at exit, not essential, it just avoids resource leaks, see #71362. */
561 const char *imports[] = {"atexit", "addon_utils", nullptr};
562 BPY_run_string_eval(C, imports, "atexit.register(addon_utils.disable_all)");
563#endif
564}
565
566void BPY_python_end(const bool do_python_exit)
567{
568#ifndef WITH_PYTHON_MODULE
569 BLI_assert_msg(Py_IsInitialized() != 0, "Python must be initialized");
570#endif
571
572 /* Finalizing, no need to grab the state, except when we are a module. */
573 PyGILState_STATE gilstate = PyGILState_Ensure();
574
575 /* Frees the Python-driver name-space & cached data. */
577
578 /* Clear Python values in the context so freeing the context after Python exits doesn't crash. */
580
581 /* Decrement user counts of all callback functions. */
583
584 /* Free other Python data. */
585 RNA_bpy_exit();
586
587 BPY_rna_exit();
588
589 /* Clear all Python data from structs. */
590
592
593 /* `bpy.app` modules that need cleanup. */
595
596#ifndef WITH_PYTHON_MODULE
597 /* Without this we get recursive calls to #WM_exit_ex. */
599
600 if (do_python_exit) {
601 Py_Finalize();
602 }
603 (void)gilstate;
604#else
605 PyGILState_Release(gilstate);
606 (void)do_python_exit;
607#endif
608
609#ifdef TIME_PY_RUN
610 /* Measure time since Python started. */
611 bpy_timer = BLI_time_now_seconds() - bpy_timer;
612
613 printf("*bpy stats* - ");
614 printf("tot exec: %d, ", bpy_timer_count);
615 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
616 if (bpy_timer_count > 0) {
617 printf("average run: %.6fsec, ", (bpy_timer_run_tot / bpy_timer_count));
618 }
619
620 if (bpy_timer > 0.0) {
621 printf("tot usage %.4f%%", (bpy_timer_run_tot / bpy_timer) * 100.0);
622 }
623
624 printf("\n");
625#endif
626}
627
629{
630 BLI_assert_msg(Py_IsInitialized() != 0, "Python must be initialized");
631
632 /* Unrelated security stuff. */
634 G.autoexec_fail[0] = '\0';
635
639}
640
642{
643 BLI_assert(!Py_IsInitialized());
644 py_use_system_env = true;
645}
646
651
653{
654 fputs("\n# Python backtrace\n", fp);
655
656 /* Can happen in rare cases. */
658 return;
659 }
660 PyFrameObject *frame = PyEval_GetFrame();
661 if (frame == nullptr) {
662 return;
663 }
664 do {
665 PyCodeObject *code = PyFrame_GetCode(frame);
666 const int line = PyFrame_GetLineNumber(frame);
667 const char *filepath = PyUnicode_AsUTF8(code->co_filename);
668 const char *funcname = PyUnicode_AsUTF8(code->co_name);
669 fprintf(fp, " File \"%s\", line %d in %s\n", filepath, line, funcname);
670 } while ((frame = PyFrame_GetBack(frame)));
671}
672
673void BPY_DECREF(void *pyob_ptr)
674{
675 const PyGILState_STATE gilstate = PyGILState_Ensure();
676 Py_DECREF((PyObject *)pyob_ptr);
677 PyGILState_Release(gilstate);
678}
679
680void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
681{
682 const PyGILState_STATE gilstate = PyGILState_Ensure();
683 const bool do_invalidate = (Py_REFCNT((PyObject *)pyob_ptr) > 1);
684 Py_DECREF((PyObject *)pyob_ptr);
685 if (do_invalidate) {
686 pyrna_invalidate(static_cast<BPy_DummyPointerRNA *>(pyob_ptr));
687 }
688 PyGILState_Release(gilstate);
689}
690
692{
693 PyGILState_STATE gilstate;
694 Main *bmain = CTX_data_main(C);
695 Text *text;
696
697 /* Can happen on file load. */
698 if (bmain == nullptr) {
699 return;
700 }
701
702 /* Update pointers since this can run from a nested script on file load. */
703 if (py_call_level) {
705 }
706
707 bpy_context_set(C, &gilstate);
708
711 {
712 LISTBASE_FOREACH (Scene *, scene, &bmain->scenes) {
713 LISTBASE_FOREACH (ViewLayer *, view_layer, &scene->view_layers) {
715 const FreestyleModuleConfig *, module_conf, &view_layer->freestyle_config.modules)
716 {
717 if (module_conf->script) {
719 SNPRINTF(G.autoexec_fail,
720 RPT_("Freestyle style module '%s'"),
721 module_conf->script->id.name + 2);
722 }
723 }
724 }
725 }
726 }
727
728 for (text = static_cast<Text *>(bmain->texts.first); text;
729 text = static_cast<Text *>(text->id.next))
730 {
731 if (text->flags & TXT_ISSCRIPT) {
732 if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
735 SNPRINTF(G.autoexec_fail, RPT_("Text '%s'"), text->id.name + 2);
736
737 printf("scripts disabled for \"%s\", skipping '%s'\n",
739 text->id.name + 2);
740 }
741 }
742 else {
743 BPY_run_text(C, text, nullptr, false);
744
745 /* Check if the script loaded a new file. */
746 if (bmain != CTX_data_main(C)) {
747 break;
748 }
749 }
750 }
751 }
752
753 bpy_context_clear(C, &gilstate);
754}
755
757{
758 PyGILState_STATE gilstate;
759 const bool use_gil = !PyC_IsInterpreterActive();
760 if (use_gil) {
761 gilstate = PyGILState_Ensure();
762 }
763
764 PyObject *pyctx;
765 PyObject *item;
766 PointerRNA *ptr = nullptr;
767 bool done = false;
768
769 pyctx = (PyObject *)CTX_py_dict_get(C);
770 item = PyDict_GetItemString(pyctx, member);
771
772 if (item == nullptr) {
773 /* Pass. */
774 }
775 else if (item == Py_None) {
776 done = true;
777 }
778 else if (BPy_StructRNA_Check(item)) {
779 ptr = &reinterpret_cast<BPy_StructRNA *>(item)->ptr.value();
780
781 // result->ptr = ((BPy_StructRNA *)item)->ptr;
784 done = true;
785 }
786 else if (PySequence_Check(item)) {
787 PyObject *seq_fast = PySequence_Fast(item, "bpy_context_get sequence conversion");
788 if (seq_fast == nullptr) {
789 PyErr_Print();
790 PyErr_Clear();
791 }
792 else {
793 const int len = PySequence_Fast_GET_SIZE(seq_fast);
794 PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
795 int i;
796
797 for (i = 0; i < len; i++) {
798 PyObject *list_item = seq_fast_items[i];
799
800 if (BPy_StructRNA_Check(list_item)) {
801 ptr = &reinterpret_cast<BPy_StructRNA *>(list_item)->ptr.value();
803 }
804 else {
806 1,
807 "'%s' list item not a valid type in sequence type '%s'",
808 member,
809 Py_TYPE(item)->tp_name);
810 }
811 }
812 Py_DECREF(seq_fast);
814 done = true;
815 }
816 }
817
818 if (done == false) {
819 if (item) {
820 CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not a valid type", member);
821 }
822 else {
823 CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not found", member);
824 }
825 }
826 else {
827 CLOG_INFO(BPY_LOG_CONTEXT, 2, "'%s' found", member);
828 }
829
830 if (use_gil) {
831 PyGILState_Release(gilstate);
832 }
833
834 return done;
835}
836
837#ifdef WITH_PYTHON_MODULE
838/* TODO: reloading the module isn't functional at the moment. */
839
840static void bpy_module_free(void *mod);
841
842/* Defined in 'creator.c' when building as a Python module. */
843extern int main_python_enter(int argc, const char **argv);
844extern void main_python_exit();
845
846static struct PyModuleDef bpy_proxy_def = {
847 /*m_base*/ PyModuleDef_HEAD_INIT,
848 /*m_name*/ "bpy",
849 /*m_doc*/ nullptr,
850 /*m_size*/ 0,
851 /*m_methods*/ nullptr,
852 /*m_slots*/ nullptr,
853 /*m_traverse*/ nullptr,
854 /*m_clear*/ nullptr,
855 /*m_free*/ bpy_module_free,
856};
857
858struct dealloc_obj {
859 PyObject_HEAD
860 /* Type-specific fields go here. */
861 PyObject *mod;
862};
863
864/* Call once `__file__` is set. */
865static void bpy_module_delay_init(PyObject *bpy_proxy)
866{
867 const int argc = 1;
868 const char *argv[2];
869
870 /* Updating the module dict below will lose the reference to `__file__`. */
871 PyObject *filepath_obj = PyModule_GetFilenameObject(bpy_proxy);
872
873 /* The file can be a relative path. */
874 const char *filepath_rel = PyUnicode_AsUTF8(filepath_obj);
875 char filepath_abs[1024];
876
877 STRNCPY(filepath_abs, filepath_rel);
878 BLI_path_abs_from_cwd(filepath_abs, sizeof(filepath_abs));
879 Py_DECREF(filepath_obj);
880
881 argv[0] = filepath_abs;
882 argv[1] = nullptr;
883
884 main_python_enter(argc, argv);
885
886 /* Initialized in #BPy_init_modules(). */
887 PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
888}
889
894static bool bpy_module_ensure_compatible_version()
895{
896 /* First check the Python version used matches the major version that Blender was built with.
897 * While this isn't essential, the error message in this case may be cryptic and misleading.
898 * NOTE: using `Py_LIMITED_API` would remove the need for this, in practice it's
899 * unlikely Blender will ever used the limited API though. */
900 const uint version_runtime = Py_Version;
901
902 uint version_compile_major = PY_VERSION_HEX >> 24;
903 uint version_compile_minor = ((PY_VERSION_HEX & 0x00ff0000) >> 16);
904 uint version_runtime_major = version_runtime >> 24;
905 uint version_runtime_minor = ((version_runtime & 0x00ff0000) >> 16);
906 if ((version_compile_major != version_runtime_major) ||
907 (version_compile_minor != version_runtime_minor))
908 {
909 PyErr_Format(PyExc_ImportError,
910 "The version of \"bpy\" was compiled with: "
911 "(%u.%u) is incompatible with: (%u.%u) used by the interpreter!",
912 version_compile_major,
913 version_compile_minor,
914 version_runtime_major,
915 version_runtime_minor);
916 return false;
917 }
918 return true;
919}
920
921static void dealloc_obj_dealloc(PyObject *self);
922
923static PyTypeObject dealloc_obj_Type;
924
925/* Use our own `dealloc` so we can free a property if we use one. */
926static void dealloc_obj_dealloc(PyObject *self)
927{
928 bpy_module_delay_init(((dealloc_obj *)self)->mod);
929
930 /* NOTE: for sub-classed `PyObject` objects
931 * we can't call #PyObject_DEL() directly or it will crash. */
932 dealloc_obj_Type.tp_free(self);
933}
934
935PyMODINIT_FUNC PyInit_bpy();
936
937PyMODINIT_FUNC PyInit_bpy()
938{
939 if (!bpy_module_ensure_compatible_version()) {
940 return nullptr; /* The error has been set. */
941 }
942
943 PyObject *bpy_proxy = PyModule_Create(&bpy_proxy_def);
944
945 /* Problem:
946 * 1) This initializing function is expected to have a private member defined - `md_def`
947 * but this is only set for CAPI defined modules (not Python packages)
948 * so we can't return `bpy_package_py` as is.
949 *
950 * 2) There is a `bpy` CAPI module for python to load which is basically all of blender,
951 * and there is `scripts/bpy/__init__.py`,
952 * we may end up having to rename this module so there is no naming conflict here eg:
953 * `from blender import bpy`
954 *
955 * 3) We don't know the file-path at this point, workaround by assigning a dummy value
956 * which calls back when its freed so the real loading can take place.
957 */
958
959 /* Assign an object which is freed after `__file__` is assigned. */
960 dealloc_obj *dob;
961
962 /* Assign dummy type. */
963 dealloc_obj_Type.tp_name = "dealloc_obj";
964 dealloc_obj_Type.tp_basicsize = sizeof(dealloc_obj);
965 dealloc_obj_Type.tp_dealloc = dealloc_obj_dealloc;
966 dealloc_obj_Type.tp_flags = Py_TPFLAGS_DEFAULT;
967
968 if (PyType_Ready(&dealloc_obj_Type) < 0) {
969 return nullptr;
970 }
971
972 dob = (dealloc_obj *)dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
973 dob->mod = bpy_proxy; /* borrow */
974 PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */
975
976 return bpy_proxy;
977}
978
979static void bpy_module_free(void * /*mod*/)
980{
981 main_python_exit();
982}
983
984#endif
985
986bool BPY_string_is_keyword(const char *str)
987{
988 /* List is from: `", ".join(['"%s"' % kw for kw in __import__("keyword").kwlist])`. */
989 const char *kwlist[] = {
990 "False", "None", "True", "and", "as", "assert", "async", "await", "break",
991 "class", "continue", "def", "del", "elif", "else", "except", "finally", "for",
992 "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not",
993 "or", "pass", "raise", "return", "try", "while", "with", "yield", nullptr,
994 };
995
996 for (int i = 0; kwlist[i]; i++) {
997 if (STREQ(str, kwlist[i])) {
998 return true;
999 }
1000 }
1001
1002 return false;
1003}
1004
1005/* -------------------------------------------------------------------- */
1011
1013{
1014 return (ch < 255 && text_check_identifier(char(ch))) || Py_UNICODE_ISALNUM(ch);
1015}
1016
1018{
1019 return (ch < 255 && text_check_identifier_nodigit(char(ch))) || Py_UNICODE_ISALPHA(ch);
1020}
1021
PyObject * AUD_initPython(void)
@ BLENDER_SYSTEM_PYTHON
const char * BKE_appdir_program_path() ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL
Definition appdir.cc:952
bool BKE_appdir_program_python_search(char *program_filepath, size_t program_filepath_maxncpy, int version_major, int version_minor) ATTR_NONNULL(1)
Definition appdir.cc:966
std::optional< std::string > BKE_appdir_folder_id(int folder_id, const char *subfolder) ATTR_WARN_UNUSED_RESULT
Definition appdir.cc:717
@ CTX_DATA_TYPE_POINTER
@ CTX_DATA_TYPE_COLLECTION
void CTX_wm_operator_poll_msg_clear(bContext *C)
Main * CTX_data_main(const bContext *C)
void CTX_data_list_add_ptr(bContextDataResult *result, const PointerRNA *ptr)
void CTX_data_pointer_set_ptr(bContextDataResult *result, const PointerRNA *ptr)
void * CTX_py_dict_get(const bContext *C)
void CTX_data_type_set(bContextDataResult *result, short type)
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL
@ G_FLAG_SCRIPT_AUTOEXEC
const char * BKE_main_blendfile_path(const Main *bmain) ATTR_NONNULL()
Definition main.cc:877
bool text_check_identifier_nodigit(char ch)
Definition text.cc:2339
int text_check_identifier_unicode(unsigned int ch)
Definition text.cc:2360
int text_check_identifier_nodigit_unicode(unsigned int ch)
Definition text.cc:2365
bool text_check_identifier(char ch)
Definition text.cc:2316
#define BLI_assert(a)
Definition BLI_assert.h:46
#define BLI_assert_msg(a, msg)
Definition BLI_assert.h:53
#define LISTBASE_FOREACH(type, var, list)
#define FILE_MAX
void BLI_setenv(const char *env, const char *val) ATTR_NONNULL(1)
#define BLI_path_join(...)
const char * BLI_getenv(const char *env) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
bool BLI_path_abs_from_cwd(char *path, size_t path_maxncpy) ATTR_NONNULL(1)
#define SNPRINTF(dst, format,...)
Definition BLI_string.h:599
char * STRNCPY(char(&dst)[N], const char *src)
Definition BLI_string.h:688
unsigned int uint
int BLI_thread_is_main(void)
Definition threads.cc:179
Platform independent time functions.
double BLI_time_now_seconds(void)
Definition time.cc:65
#define UNLIKELY(x)
#define STREQ(a, b)
#define RPT_(msgid)
bool BPY_string_is_keyword(const char *str)
void BPY_context_dict_clear_members_array(void **dict_p, void *dict_orig, const char *context_members[], uint context_members_len)
int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
void BPY_modules_update()
void BPY_context_set(bContext *C)
void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
void BPY_context_update(bContext *C)
void BPY_text_free_code(Text *text)
void BPY_driver_reset()
void BPY_driver_exit()
void BPY_modules_load_user(bContext *C)
void BPY_app_handlers_reset(bool do_all)
void BPY_DECREF(void *pyob_ptr)
struct CLG_LogRef * BPY_LOG_RNA
struct CLG_LogRef * BPY_LOG_CONTEXT
void BPY_python_end(bool do_python_exit)
void BPY_python_use_system_env()
void BPY_python_backtrace(FILE *fp)
void BPY_python_reset(bContext *C)
bool BPY_python_use_system_env_get()
void BPY_python_start(bContext *C, int argc, const char **argv)
bool bool BPY_run_text(bContext *C, Text *text, ReportList *reports, bool do_jump) ATTR_NONNULL(1
bool BPY_run_string_eval(bContext *C, const char *imports[], const char *expr)
void * CCL_python_module_init(void)
Definition python.cpp:810
#define CLG_LOGREF_DECLARE_GLOBAL(var, id)
Definition CLG_log.h:145
#define CLOG_INFO(clg_ref, level,...)
Definition CLG_log.h:179
@ TXT_ISSCRIPT
#define C
Definition RandGen.cpp:29
PyObject * BPyInit_bgl()
Definition bgl.cc:2655
PyMODINIT_FUNC BPyInit_bl_math()
PyObject * BPyInit_blf()
PyObject * BPyInit_bmesh()
PyObject * BPyInit_bmesh_geometry()
PyObject * BPyInit_bmesh_types()
PyObject * BPyInit_bmesh_utils()
PyObject * bpy_package_py
Definition bpy.cc:63
void BPy_init_modules(bContext *C)
Definition bpy.cc:725
void BPY_atexit_unregister()
void BPY_atexit_register()
struct CLG_LogRef * BPY_LOG_INTERFACE
void BPY_app_translations_end()
void bpy_context_clear(struct bContext *C, const PyGILState_STATE *gilstate)
void bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate)
struct bContext * BPY_context_get()
static void pystatus_exit_on_error(const PyStatus &status)
static int py_call_level
static void bpy_context_end(bContext *C)
static bool py_use_system_env
static _inittab bpy_internal_modules[]
void bpy_intern_string_exit()
void bpy_intern_string_init()
PyObject * BPyInit__bpy_path()
Definition bpy_path.cc:35
void BPY_rna_props_clear_all()
void pyrna_invalidate(BPy_DummyPointerRNA *self)
Definition bpy_rna.cc:179
PyObject * BPY_rna_module()
Definition bpy_rna.cc:8593
void BPY_rna_init()
Definition bpy_rna.cc:8517
void BPY_rna_exit()
Definition bpy_rna.cc:8570
PyObject * BPY_rna_types()
Definition bpy_rna.cc:8758
void pyrna_alloc_types()
Definition bpy_rna.cc:9909
void BPY_update_rna_module()
Definition bpy_rna.cc:8605
BPy_StructRNA * bpy_context_module
Definition bpy_rna.cc:94
#define BPy_StructRNA_Check(v)
Definition bpy_rna.hh:73
#define str(s)
VecBase< float, D > constexpr mod(VecOp< float, D >, VecOp< float, D >) RET
#define printf(...)
PyObject * BPyInit_gpu()
Definition gpu_py_api.cc:48
PyObject * BPyInit_idprop()
PyObject * BPyInit_imbuf()
PyObject * Manta_initPython(void)
ccl_device_inline float len(const float2 a)
PyMODINIT_FUNC PyInit_mathutils()
Definition mathutils.cc:781
PyMODINIT_FUNC PyInit_mathutils_geometry()
PyMODINIT_FUNC PyInit_mathutils_kdtree()
PyMODINIT_FUNC PyInit_mathutils_noise()
#define G(x, y, z)
bool PyC_IsInterpreterActive()
PyObject * BPyInit_hydra()
Definition python.cc:209
header-only compatibility defines.
#define PyThreadState_GetUnchecked
void RNA_bpy_exit()
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:130
void * next
Definition DNA_ID.h:407
char name[66]
Definition DNA_ID.h:415
void * first
ListBase scenes
Definition BKE_main.hh:245
ListBase texts
Definition BKE_main.hh:263
int flags
void * compiled
i
Definition text_draw.cc:230