Blender  V2.93
bpy_interface.c
Go to the documentation of this file.
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  * Chris Keith, Chris Want, Ken Hughes, Campbell Barton
17  */
18 
27 #include <Python.h>
28 #include <frameobject.h>
29 
30 #include "MEM_guardedalloc.h"
31 
32 #include "CLG_log.h"
33 
34 #include "BLI_fileops.h"
35 #include "BLI_listbase.h"
36 #include "BLI_path_util.h"
37 #include "BLI_string.h"
38 #include "BLI_string_utf8.h"
39 #include "BLI_threads.h"
40 #include "BLI_utildefines.h"
41 
42 #include "RNA_types.h"
43 
44 #include "bpy.h"
45 #include "bpy_capi_utils.h"
46 #include "bpy_intern_string.h"
47 #include "bpy_path.h"
48 #include "bpy_props.h"
49 #include "bpy_rna.h"
50 #include "bpy_traceback.h"
51 
52 #include "bpy_app_translations.h"
53 
54 #include "DNA_text_types.h"
55 
56 #include "BKE_appdir.h"
57 #include "BKE_context.h"
58 #include "BKE_global.h" /* only for script checking */
59 #include "BKE_main.h"
60 #include "BKE_text.h"
61 
62 #ifdef WITH_CYCLES
63 # include "CCL_api.h"
64 #endif
65 
66 #include "BPY_extern.h"
67 #include "BPY_extern_python.h"
68 #include "BPY_extern_run.h"
69 
70 #include "../generic/py_capi_utils.h"
71 
72 /* inittab initialization functions */
73 #include "../bmesh/bmesh_py_api.h"
74 #include "../generic/bgl.h"
75 #include "../generic/bl_math_py_api.h"
76 #include "../generic/blf_py_api.h"
77 #include "../generic/idprop_py_api.h"
78 #include "../generic/imbuf_py_api.h"
79 #include "../gpu/gpu_py_api.h"
80 #include "../mathutils/mathutils.h"
81 
82 /* Logging types to use anywhere in the Python modules. */
86 
87 /* for internal use, when starting and ending python scripts */
88 
89 /* In case a python script triggers another python call,
90  * stop bpy_context_clear from invalidating. */
91 static int py_call_level = 0;
92 
93 /* Set by command line arguments before Python starts. */
94 static bool py_use_system_env = false;
95 
96 // #define TIME_PY_RUN /* simple python tests. prints on exit. */
97 
98 #ifdef TIME_PY_RUN
99 # include "PIL_time.h"
100 static int bpy_timer_count = 0;
101 static double bpy_timer; /* time since python starts */
102 static double bpy_timer_run; /* time for each python script run */
103 static double bpy_timer_run_tot; /* accumulate python runs */
104 #endif
105 
106 /* use for updating while a python script runs - in case of file load */
108 {
109  /* don't do this from a non-main (e.g. render) thread, it can cause a race
110  * condition on C->data.recursion. ideal solution would be to disable
111  * context entirely from non-main threads, but that's more complicated */
112  if (!BLI_thread_is_main()) {
113  return;
114  }
115 
117  BPY_modules_update(); /* can give really bad results if this isn't here */
118 }
119 
120 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
121 {
122  py_call_level++;
123 
124  if (gilstate) {
125  *gilstate = PyGILState_Ensure();
126  }
127 
128  if (py_call_level == 1) {
130 
131 #ifdef TIME_PY_RUN
132  if (bpy_timer_count == 0) {
133  /* record time from the beginning */
134  bpy_timer = PIL_check_seconds_timer();
135  bpy_timer_run = bpy_timer_run_tot = 0.0;
136  }
137  bpy_timer_run = PIL_check_seconds_timer();
138 
139  bpy_timer_count++;
140 #endif
141  }
142 }
143 
144 /* context should be used but not now because it causes some bugs */
145 void bpy_context_clear(bContext *UNUSED(C), const PyGILState_STATE *gilstate)
146 {
147  py_call_level--;
148 
149  if (gilstate) {
150  PyGILState_Release(*gilstate);
151  }
152 
153  if (py_call_level < 0) {
154  fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
155  }
156  else if (py_call_level == 0) {
157  /* XXX - Calling classes currently wont store the context :\,
158  * cant set NULL because of this. but this is very flakey still. */
159 #if 0
161 #endif
162 
163 #ifdef TIME_PY_RUN
164  bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
165  bpy_timer_count++;
166 #endif
167  }
168 }
169 
181  void *dict_orig,
182  const char *context_members[],
183  uint context_members_len)
184 {
185  PyGILState_STATE gilstate;
186  const bool use_gil = !PyC_IsInterpreterActive();
187 
188  if (use_gil) {
189  gilstate = PyGILState_Ensure();
190  }
191 
192  /* Copy on write. */
193  if (*dict_p == dict_orig) {
194  *dict_p = PyDict_Copy(dict_orig);
195  }
196 
197  PyObject *dict = *dict_p;
198  BLI_assert(PyDict_Check(dict));
199 
200  /* Use #PyDict_Pop instead of #PyDict_DelItemString to avoid setting the exception,
201  * while supported it's good to avoid for low level functions like this that run often. */
202  for (uint i = 0; i < context_members_len; i++) {
203  PyObject *key = PyUnicode_FromString(context_members[i]);
204  PyObject *item = _PyDict_Pop(dict, key, Py_None);
205  Py_DECREF(key);
206  Py_DECREF(item);
207  }
208 
209  if (use_gil) {
210  PyGILState_Release(gilstate);
211  }
212 }
213 
215 {
216  if (text->compiled) {
217  PyGILState_STATE gilstate;
218  const bool use_gil = !PyC_IsInterpreterActive();
219 
220  if (use_gil) {
221  gilstate = PyGILState_Ensure();
222  }
223 
224  Py_DECREF((PyObject *)text->compiled);
225  text->compiled = NULL;
226 
227  if (use_gil) {
228  PyGILState_Release(gilstate);
229  }
230  }
231 }
232 
237 {
238 #if 0 /* slow, this runs all the time poll, draw etc 100's of time a sec. */
239  PyObject *mod = PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
240  PyModule_AddObject(mod, "data", BPY_rna_module());
241  PyModule_AddObject(mod, "types", BPY_rna_types()); /* atm this does not need updating */
242 #endif
243 
244  /* refreshes the main struct */
246 }
247 
249 {
250  return bpy_context_module->ptr.data;
251 }
252 
254 {
255  bpy_context_module->ptr.data = (void *)C;
256 }
257 
258 #ifdef WITH_FLUID
259 /* defined in manta module */
260 extern PyObject *Manta_initPython(void);
261 #endif
262 
263 #ifdef WITH_AUDASPACE
264 /* defined in AUD_C-API.cpp */
265 extern PyObject *AUD_initPython(void);
266 #endif
267 
268 #ifdef WITH_CYCLES
269 /* defined in cycles module */
270 static PyObject *CCL_initPython(void)
271 {
272  return (PyObject *)CCL_python_module_init();
273 }
274 #endif
275 
276 static struct _inittab bpy_internal_modules[] = {
277  {"mathutils", PyInit_mathutils},
278 #if 0
279  {"mathutils.geometry", PyInit_mathutils_geometry},
280  {"mathutils.noise", PyInit_mathutils_noise},
281  {"mathutils.kdtree", PyInit_mathutils_kdtree},
282 #endif
283  {"_bpy_path", BPyInit__bpy_path},
284  {"bgl", BPyInit_bgl},
285  {"blf", BPyInit_blf},
286  {"bl_math", BPyInit_bl_math},
287  {"imbuf", BPyInit_imbuf},
288  {"bmesh", BPyInit_bmesh},
289 #if 0
290  {"bmesh.types", BPyInit_bmesh_types},
291  {"bmesh.utils", BPyInit_bmesh_utils},
292  {"bmesh.utils", BPyInit_bmesh_geometry},
293 #endif
294 #ifdef WITH_FLUID
295  {"manta", Manta_initPython},
296 #endif
297 #ifdef WITH_AUDASPACE
298  {"aud", AUD_initPython},
299 #endif
300 #ifdef WITH_CYCLES
301  {"_cycles", CCL_initPython},
302 #endif
303  {"gpu", BPyInit_gpu},
304  {"idprop", BPyInit_idprop},
305  {NULL, NULL},
306 };
307 
308 #ifndef WITH_PYTHON_MODULE
318 static void pystatus_exit_on_error(PyStatus status)
319 {
320  if (UNLIKELY(PyStatus_Exception(status))) {
321  fputs("Internal error initializing Python!\n", stderr);
322  /* This calls `exit`. */
323  Py_ExitStatusException(status);
324  }
325 }
326 #endif
327 
328 /* call BPY_context_set first */
329 void BPY_python_start(bContext *C, int argc, const char **argv)
330 {
331 #ifndef WITH_PYTHON_MODULE
332 
333  /* #PyPreConfig (early-configuration). */
334  {
335  PyPreConfig preconfig;
336  PyStatus status;
337 
338  if (py_use_system_env) {
339  PyPreConfig_InitPythonConfig(&preconfig);
340  }
341  else {
342  /* Only use the systems environment variables and site when explicitly requested.
343  * Since an incorrect 'PYTHONPATH' causes difficult to debug errors, see: T72807.
344  * An alternative to setting `preconfig.use_environment = 0` */
345  PyPreConfig_InitIsolatedConfig(&preconfig);
346  }
347 
348  /* Force `utf-8` on all platforms, since this is what's used for Blender's internal strings,
349  * providing consistent encoding behavior across all Blender installations.
350  *
351  * This also uses the `surrogateescape` error handler ensures any unexpected bytes are escaped
352  * instead of raising an error.
353  *
354  * Without this `sys.getfilesystemencoding()` and `sys.stdout` for example may be set to ASCII
355  * or some other encoding - where printing some `utf-8` values will raise an error.
356  *
357  * This can cause scripts to fail entirely on some systems.
358  *
359  * This assignment is the equivalent of enabling the `PYTHONUTF8` environment variable.
360  * See `PEP-540` for details on exactly what this changes. */
361  preconfig.utf8_mode = true;
362 
363  /* Note that there is no reason to call #Py_PreInitializeFromBytesArgs here
364  * as this is only used so that command line arguments can be handled by Python itself,
365  * not for setting `sys.argv` (handled below). */
366  status = Py_PreInitialize(&preconfig);
367  pystatus_exit_on_error(status);
368  }
369 
370  /* Must run before python initializes, but after #PyPreConfig. */
371  PyImport_ExtendInittab(bpy_internal_modules);
372 
373  /* #PyConfig (initialize Python). */
374  {
375  PyConfig config;
376  PyStatus status;
377  bool has_python_executable = false;
378 
379  PyConfig_InitPythonConfig(&config);
380 
381  /* Suppress error messages when calculating the module search path.
382  * While harmless, it's noisy. */
383  config.pathconfig_warnings = 0;
384 
385  /* When using the system's Python, allow the site-directory as well. */
386  config.user_site_directory = py_use_system_env;
387 
388  /* While `sys.argv` is set, we don't want Python to interpret it. */
389  config.parse_argv = 0;
390  status = PyConfig_SetBytesArgv(&config, argc, (char *const *)argv);
391  pystatus_exit_on_error(status);
392 
393  /* Needed for Python's initialization for portable Python installations.
394  * We could use #Py_SetPath, but this overrides Python's internal logic
395  * for calculating it's own module search paths.
396  *
397  * `sys.executable` is overwritten after initialization to the Python binary. */
398  {
399  const char *program_path = BKE_appdir_program_path();
400  status = PyConfig_SetBytesString(&config, &config.program_name, program_path);
401  pystatus_exit_on_error(status);
402  }
403 
404  /* Setting the program name is important so the 'multiprocessing' module
405  * can launch new Python instances. */
406  {
407  char program_path[FILE_MAX];
409  program_path, sizeof(program_path), PY_MAJOR_VERSION, PY_MINOR_VERSION)) {
410  status = PyConfig_SetBytesString(&config, &config.executable, program_path);
411  pystatus_exit_on_error(status);
412  has_python_executable = true;
413  }
414  else {
415  /* Set to `sys.executable = None` below (we can't do before Python is initialized). */
416  fprintf(stderr,
417  "Unable to find the python binary, "
418  "the multiprocessing module may not be functional!\n");
419  }
420  }
421 
422  /* Allow to use our own included Python. `py_path_bundle` may be NULL. */
423  {
424  const char *py_path_bundle = BKE_appdir_folder_id(BLENDER_SYSTEM_PYTHON, NULL);
425  if (py_path_bundle != NULL) {
426 
427 # ifdef __APPLE__
428  /* Mac-OS allows file/directory names to contain `:` character
429  * (represented as `/` in the Finder) but current Python lib (as of release 3.1.1)
430  * doesn't handle these correctly. */
431  if (strchr(py_path_bundle, ':')) {
432  fprintf(stderr,
433  "Warning! Blender application is located in a path containing ':' or '/' chars\n"
434  "This may make python import function fail\n");
435  }
436 # endif /* __APPLE__ */
437 
438  status = PyConfig_SetBytesString(&config, &config.home, py_path_bundle);
439  pystatus_exit_on_error(status);
440  }
441  else {
442  /* Common enough to use the system Python on Linux/Unix, warn on other systems. */
443 # if defined(__APPLE__) || defined(_WIN32)
444  fprintf(stderr,
445  "Bundled Python not found and is expected on this platform "
446  "(the 'install' target may have not been built)\n");
447 # endif
448  }
449  }
450 
451  /* Initialize Python (also acquires lock). */
452  status = Py_InitializeFromConfig(&config);
453  pystatus_exit_on_error(status);
454 
455  if (!has_python_executable) {
456  PySys_SetObject("executable", Py_None);
457  }
458  }
459 
460 # ifdef WITH_FLUID
461  /* Required to prevent assertion error, see:
462  * https://stackoverflow.com/questions/27844676 */
463  Py_DECREF(PyImport_ImportModule("threading"));
464 # endif
465 
466 #else
467  (void)argc;
468  (void)argv;
469 
470  /* must run before python initializes */
471  /* broken in py3.3, load explicitly below */
472  // PyImport_ExtendInittab(bpy_internal_modules);
473 #endif
474 
476 
477 #ifdef WITH_PYTHON_MODULE
478  {
479  /* Manually load all modules */
480  struct _inittab *inittab_item;
481  PyObject *sys_modules = PyImport_GetModuleDict();
482 
483  for (inittab_item = bpy_internal_modules; inittab_item->name; inittab_item++) {
484  PyObject *mod = inittab_item->initfunc();
485  if (mod) {
486  PyDict_SetItemString(sys_modules, inittab_item->name, mod);
487  }
488  else {
489  PyErr_Print();
490  PyErr_Clear();
491  }
492  // Py_DECREF(mod); /* ideally would decref, but in this case we never want to free */
493  }
494  }
495 #endif
496 
497  /* bpy.* and lets us import it */
499 
501 
502 #ifndef WITH_PYTHON_MODULE
503  /* py module runs atexit when bpy is freed */
504  BPY_atexit_register(); /* this can init any time */
505 
506  /* Free the lock acquired (implicitly) when Python is initialized. */
507  PyEval_ReleaseThread(PyGILState_GetThisThreadState());
508 
509 #endif
510 
511 #ifdef WITH_PYTHON_MODULE
512  /* Disable all add-ons at exit, not essential, it just avoids resource leaks, see T71362. */
514  (const char *[]){"atexit", "addon_utils", NULL},
515  "atexit.register(addon_utils.disable_all)");
516 #endif
517 }
518 
519 void BPY_python_end(void)
520 {
521  // fprintf(stderr, "Ending Python!\n");
522  PyGILState_STATE gilstate;
523 
524  /* finalizing, no need to grab the state, except when we are a module */
525  gilstate = PyGILState_Ensure();
526 
527  /* Decrement user counts of all callback functions. */
529 
530  /* free other python data. */
532 
533  /* clear all python data from structs */
534 
536 
537  /* bpy.app modules that need cleanup */
539 
540 #ifndef WITH_PYTHON_MODULE
541  BPY_atexit_unregister(); /* without this we get recursive calls to WM_exit */
542 
543  Py_Finalize();
544 
545  (void)gilstate;
546 #else
547  PyGILState_Release(gilstate);
548 #endif
549 
550 #ifdef TIME_PY_RUN
551  /* measure time since py started */
552  bpy_timer = PIL_check_seconds_timer() - bpy_timer;
553 
554  printf("*bpy stats* - ");
555  printf("tot exec: %d, ", bpy_timer_count);
556  printf("tot run: %.4fsec, ", bpy_timer_run_tot);
557  if (bpy_timer_count > 0) {
558  printf("average run: %.6fsec, ", (bpy_timer_run_tot / bpy_timer_count));
559  }
560 
561  if (bpy_timer > 0.0) {
562  printf("tot usage %.4f%%", (bpy_timer_run_tot / bpy_timer) * 100.0);
563  }
564 
565  printf("\n");
566 
567  // fprintf(stderr, "Ending Python Done!\n");
568 
569 #endif
570 }
571 
573 {
574  /* unrelated security stuff */
576  G.autoexec_fail[0] = '\0';
577 
579  BPY_app_handlers_reset(false);
581 }
582 
584 {
585  BLI_assert(!Py_IsInitialized());
586  py_use_system_env = true;
587 }
588 
589 void BPY_python_backtrace(FILE *fp)
590 {
591  fputs("\n# Python backtrace\n", fp);
592  PyThreadState *tstate = PyGILState_GetThisThreadState();
593  if (tstate != NULL && tstate->frame != NULL) {
594  PyFrameObject *frame = tstate->frame;
595  do {
596  const int line = PyCode_Addr2Line(frame->f_code, frame->f_lasti);
597  const char *filename = PyUnicode_AsUTF8(frame->f_code->co_filename);
598  const char *funcname = PyUnicode_AsUTF8(frame->f_code->co_name);
599  fprintf(fp, " File \"%s\", line %d in %s\n", filename, line, funcname);
600  } while ((frame = frame->f_back));
601  }
602 }
603 
604 void BPY_DECREF(void *pyob_ptr)
605 {
606  const PyGILState_STATE gilstate = PyGILState_Ensure();
607  Py_DECREF((PyObject *)pyob_ptr);
608  PyGILState_Release(gilstate);
609 }
610 
611 void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
612 {
613  const PyGILState_STATE gilstate = PyGILState_Ensure();
614  const bool do_invalidate = (Py_REFCNT((PyObject *)pyob_ptr) > 1);
615  Py_DECREF((PyObject *)pyob_ptr);
616  if (do_invalidate) {
617  pyrna_invalidate(pyob_ptr);
618  }
619  PyGILState_Release(gilstate);
620 }
621 
623 {
624  PyGILState_STATE gilstate;
625  Main *bmain = CTX_data_main(C);
626  Text *text;
627 
628  /* can happen on file load */
629  if (bmain == NULL) {
630  return;
631  }
632 
633  /* update pointers since this can run from a nested script
634  * on file load */
635  if (py_call_level) {
637  }
638 
639  bpy_context_set(C, &gilstate);
640 
641  for (text = bmain->texts.first; text; text = text->id.next) {
642  if (text->flags & TXT_ISSCRIPT && BLI_path_extension_check(text->id.name + 2, ".py")) {
643  if (!(G.f & G_FLAG_SCRIPT_AUTOEXEC)) {
646  BLI_snprintf(G.autoexec_fail, sizeof(G.autoexec_fail), "Text '%s'", text->id.name + 2);
647 
648  printf("scripts disabled for \"%s\", skipping '%s'\n",
650  text->id.name + 2);
651  }
652  }
653  else {
654  BPY_run_text(C, text, NULL, false);
655 
656  /* Check if the script loaded a new file. */
657  if (bmain != CTX_data_main(C)) {
658  break;
659  }
660  }
661  }
662  }
663  bpy_context_clear(C, &gilstate);
664 }
665 
667 {
668  PyGILState_STATE gilstate;
669  const bool use_gil = !PyC_IsInterpreterActive();
670 
671  PyObject *pyctx;
672  PyObject *item;
673  PointerRNA *ptr = NULL;
674  bool done = false;
675 
676  if (use_gil) {
677  gilstate = PyGILState_Ensure();
678  }
679 
680  pyctx = (PyObject *)CTX_py_dict_get(C);
681  item = PyDict_GetItemString(pyctx, member);
682 
683  if (item == NULL) {
684  /* pass */
685  }
686  else if (item == Py_None) {
687  done = true;
688  }
689  else if (BPy_StructRNA_Check(item)) {
690  ptr = &(((BPy_StructRNA *)item)->ptr);
691 
692  // result->ptr = ((BPy_StructRNA *)item)->ptr;
695  done = true;
696  }
697  else if (PySequence_Check(item)) {
698  PyObject *seq_fast = PySequence_Fast(item, "bpy_context_get sequence conversion");
699  if (seq_fast == NULL) {
700  PyErr_Print();
701  PyErr_Clear();
702  }
703  else {
704  const int len = PySequence_Fast_GET_SIZE(seq_fast);
705  PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
706  int i;
707 
708  for (i = 0; i < len; i++) {
709  PyObject *list_item = seq_fast_items[i];
710 
711  if (BPy_StructRNA_Check(list_item)) {
712 #if 0
714  "bpy_context_get");
715  link->ptr = ((BPy_StructRNA *)item)->ptr;
716  BLI_addtail(&result->list, link);
717 #endif
718  ptr = &(((BPy_StructRNA *)list_item)->ptr);
720  }
721  else {
723  1,
724  "'%s' list item not a valid type in sequence type '%s'",
725  member,
726  Py_TYPE(item)->tp_name);
727  }
728  }
729  Py_DECREF(seq_fast);
731  done = true;
732  }
733  }
734 
735  if (done == false) {
736  if (item) {
737  CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not a valid type", member);
738  }
739  else {
740  CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not found\n", member);
741  }
742  }
743  else {
744  CLOG_INFO(BPY_LOG_CONTEXT, 2, "'%s' found", member);
745  }
746 
747  if (use_gil) {
748  PyGILState_Release(gilstate);
749  }
750 
751  return done;
752 }
753 
754 #ifdef WITH_PYTHON_MODULE
755 /* TODO, reloading the module isn't functional at the moment. */
756 
757 static void bpy_module_free(void *mod);
758 
759 /* Defined in 'creator.c' when building as a Python module. */
760 extern int main_python_enter(int argc, const char **argv);
761 extern void main_python_exit(void);
762 
763 static struct PyModuleDef bpy_proxy_def = {
764  PyModuleDef_HEAD_INIT,
765  "bpy", /* m_name */
766  NULL, /* m_doc */
767  0, /* m_size */
768  NULL, /* m_methods */
769  NULL, /* m_reload */
770  NULL, /* m_traverse */
771  NULL, /* m_clear */
772  bpy_module_free, /* m_free */
773 };
774 
775 typedef struct {
776  PyObject_HEAD
777  /* Type-specific fields go here. */
778  PyObject *mod;
779 } dealloc_obj;
780 
781 /* call once __file__ is set */
782 static void bpy_module_delay_init(PyObject *bpy_proxy)
783 {
784  const int argc = 1;
785  const char *argv[2];
786 
787  /* updating the module dict below will lose the reference to __file__ */
788  PyObject *filename_obj = PyModule_GetFilenameObject(bpy_proxy);
789 
790  const char *filename_rel = PyUnicode_AsUTF8(filename_obj); /* can be relative */
791  char filename_abs[1024];
792 
793  BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
794  BLI_path_abs_from_cwd(filename_abs, sizeof(filename_abs));
795  Py_DECREF(filename_obj);
796 
797  argv[0] = filename_abs;
798  argv[1] = NULL;
799 
800  // printf("module found %s\n", argv[0]);
801 
802  main_python_enter(argc, argv);
803 
804  /* initialized in BPy_init_modules() */
805  PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
806 }
807 
808 static void dealloc_obj_dealloc(PyObject *self);
809 
810 static PyTypeObject dealloc_obj_Type;
811 
812 /* use our own dealloc so we can free a property if we use one */
813 static void dealloc_obj_dealloc(PyObject *self)
814 {
815  bpy_module_delay_init(((dealloc_obj *)self)->mod);
816 
817  /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
818  dealloc_obj_Type.tp_free(self);
819 }
820 
821 PyMODINIT_FUNC PyInit_bpy(void);
822 
823 PyMODINIT_FUNC PyInit_bpy(void)
824 {
825  PyObject *bpy_proxy = PyModule_Create(&bpy_proxy_def);
826 
827  /* Problem:
828  * 1) this init function is expected to have a private member defined - 'md_def'
829  * but this is only set for C defined modules (not py packages)
830  * so we cant return 'bpy_package_py' as is.
831  *
832  * 2) there is a 'bpy' C module for python to load which is basically all of blender,
833  * and there is scripts/bpy/__init__.py,
834  * we may end up having to rename this module so there is no naming conflict here eg:
835  * 'from blender import bpy'
836  *
837  * 3) we don't know the filename at this point, workaround by assigning a dummy value
838  * which calls back when its freed so the real loading can take place.
839  */
840 
841  /* assign an object which is freed after __file__ is assigned */
842  dealloc_obj *dob;
843 
844  /* assign dummy type */
845  dealloc_obj_Type.tp_name = "dealloc_obj";
846  dealloc_obj_Type.tp_basicsize = sizeof(dealloc_obj);
847  dealloc_obj_Type.tp_dealloc = dealloc_obj_dealloc;
848  dealloc_obj_Type.tp_flags = Py_TPFLAGS_DEFAULT;
849 
850  if (PyType_Ready(&dealloc_obj_Type) < 0) {
851  return NULL;
852  }
853 
854  dob = (dealloc_obj *)dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
855  dob->mod = bpy_proxy; /* borrow */
856  PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */
857 
858  return bpy_proxy;
859 }
860 
861 static void bpy_module_free(void *UNUSED(mod))
862 {
863  main_python_exit();
864 }
865 
866 #endif
867 
871 bool BPY_string_is_keyword(const char *str)
872 {
873  /* list is from...
874  * ", ".join(['"%s"' % kw for kw in __import__("keyword").kwlist])
875  */
876  const char *kwlist[] = {
877  "False", "None", "True", "and", "as", "assert", "async", "await", "break",
878  "class", "continue", "def", "del", "elif", "else", "except", "finally", "for",
879  "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not",
880  "or", "pass", "raise", "return", "try", "while", "with", "yield", NULL,
881  };
882 
883  for (int i = 0; kwlist[i]; i++) {
884  if (STREQ(str, kwlist[i])) {
885  return true;
886  }
887  }
888 
889  return false;
890 }
891 
892 /* EVIL, define text.c functions here... */
893 /* BKE_text.h */
895 {
896  return (ch < 255 && text_check_identifier((char)ch)) || Py_UNICODE_ISALNUM(ch);
897 }
898 
900 {
901  return (ch < 255 && text_check_identifier_nodigit((char)ch)) || Py_UNICODE_ISALPHA(ch);
902 }
PyObject * AUD_initPython(void)
Definition: AUD_PyInit.cpp:67
@ BLENDER_SYSTEM_PYTHON
Definition: BKE_appdir.h:89
bool BKE_appdir_program_python_search(char *fullpath, const size_t fullpath_len, const int version_major, const int version_minor)
Definition: appdir.c:897
const char * BKE_appdir_folder_id(const int folder_id, const char *subfolder)
Definition: appdir.c:674
const char * BKE_appdir_program_path(void)
Definition: appdir.c:882
void CTX_data_pointer_set(bContextDataResult *result, struct ID *id, StructRNA *type, void *data)
Definition: context.c:638
void * CTX_py_dict_get(const bContext *C)
Definition: context.c:224
@ CTX_DATA_TYPE_POINTER
Definition: BKE_context.h:220
@ CTX_DATA_TYPE_COLLECTION
Definition: BKE_context.h:221
void CTX_data_list_add(bContextDataResult *result, struct ID *id, StructRNA *type, void *data)
Definition: context.c:651
void CTX_data_type_set(struct bContextDataResult *result, short type)
Definition: context.c:677
struct Main * CTX_data_main(const bContext *C)
Definition: context.c:1018
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL_QUIET
Definition: BKE_global.h:120
@ G_FLAG_SCRIPT_AUTOEXEC_FAIL
Definition: BKE_global.h:119
@ G_FLAG_SCRIPT_AUTOEXEC
Definition: BKE_global.h:116
const char * BKE_main_blendfile_path(const struct Main *bmain) ATTR_NONNULL()
bool text_check_identifier(const char ch)
Definition: text.c:2426
bool text_check_identifier_nodigit(const char ch)
Definition: text.c:2449
#define BLI_assert(a)
Definition: BLI_assert.h:58
File and directory operations.
void BLI_addtail(struct ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition: listbase.c:110
#define FILE_MAX
bool BLI_path_abs_from_cwd(char *path, const size_t maxlen) ATTR_NONNULL()
Definition: path_util.c:1128
bool BLI_path_extension_check(const char *str, const char *ext) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT
Definition: path_util.c:1459
size_t BLI_snprintf(char *__restrict dst, size_t maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, const size_t maxncpy) ATTR_NONNULL()
Definition: string.c:108
unsigned int uint
Definition: BLI_sys_types.h:83
int BLI_thread_is_main(void)
Definition: threads.cc:234
#define UNUSED(x)
#define UNLIKELY(x)
#define STREQ(a, b)
void BPY_app_handlers_reset(const short do_all)
void BPY_driver_reset(void)
Definition: bpy_driver.c:228
struct CLG_LogRef * BPY_LOG_RNA
struct CLG_LogRef * BPY_LOG_CONTEXT
bool BPY_run_string_eval(struct bContext *C, const char *imports[], const char *expr)
bool BPY_run_text(struct bContext *C, struct Text *text, struct ReportList *reports, const bool do_jump)
#define CLOG_INFO(clg_ref, level,...)
Definition: CLG_log.h:201
@ TXT_ISSCRIPT
Read Guarded memory(de)allocation.
Platform independent time functions.
#define C
Definition: RandGen.cpp:39
PyObject * BPyInit_bgl(void)
Definition: bgl.c:2594
PyMODINIT_FUNC BPyInit_bl_math(void)
CCL_NAMESPACE_END void * CCL_python_module_init()
PyObject * BPyInit_blf(void)
Definition: blf_py_api.c:487
PyObject * BPyInit_bmesh(void)
Definition: bmesh_py_api.c:185
PyObject * BPyInit_bmesh_geometry(void)
PyObject * BPyInit_bmesh_types(void)
PyObject * BPyInit_bmesh_utils(void)
void BPy_init_modules(struct bContext *C)
Definition: bpy.c:391
PyObject * bpy_package_py
Definition: bpy.c:65
void BPY_atexit_register(void)
struct CLG_LogRef * BPY_LOG_INTERFACE
void BPY_atexit_unregister(void)
void BPY_app_translations_end(void)
int text_check_identifier_nodigit_unicode(const uint ch)
bContext * BPY_context_get(void)
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 text_check_identifier_unicode(const uint ch)
int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
void BPY_context_set(bContext *C)
void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
static void pystatus_exit_on_error(PyStatus status)
void BPY_python_backtrace(FILE *fp)
void BPY_python_use_system_env(void)
static int py_call_level
Definition: bpy_interface.c:91
void BPY_modules_update(void)
CLG_LOGREF_DECLARE_GLOBAL(BPY_LOG_CONTEXT, "bpy.context")
void BPY_python_reset(bContext *C)
static bool py_use_system_env
Definition: bpy_interface.c:94
void BPY_context_update(bContext *C)
void BPY_python_end(void)
static struct _inittab bpy_internal_modules[]
void BPY_text_free_code(Text *text)
void bpy_context_clear(bContext *UNUSED(C), const PyGILState_STATE *gilstate)
void BPY_modules_load_user(bContext *C)
void BPY_python_start(bContext *C, int argc, const char **argv)
void BPY_DECREF(void *pyob_ptr)
void bpy_intern_string_init(void)
void bpy_intern_string_exit(void)
PyObject * BPyInit__bpy_path(void)
Definition: bpy_path.c:49
void BPY_rna_props_clear_all(void)
Definition: bpy_props.c:3967
void pyrna_invalidate(BPy_DummyPointerRNA *self)
Definition: bpy_rna.c:133
void pyrna_alloc_types(void)
Definition: bpy_rna.c:8743
void pyrna_free_types(void)
Definition: bpy_rna.c:8775
void BPY_update_rna_module(void)
Definition: bpy_rna.c:7701
PyObject * BPY_rna_module(void)
Definition: bpy_rna.c:7688
PyObject * BPY_rna_types(void)
Definition: bpy_rna.c:7819
BPy_StructRNA * bpy_context_module
Definition: bpy_rna.c:97
#define BPy_StructRNA_Check(v)
Definition: bpy_rna.h:80
#define str(s)
PyObject * BPyInit_gpu(void)
Definition: gpu_py_api.c:53
PyObject * BPyInit_idprop(void)
PyObject * BPyInit_imbuf(void)
Definition: imbuf_py_api.c:558
void *(* MEM_callocN)(size_t len, const char *str)
Definition: mallocn.c:45
PyObject * Manta_initPython(void)
PyMODINIT_FUNC PyInit_mathutils(void)
Definition: mathutils.c:763
PyMODINIT_FUNC PyInit_mathutils_geometry(void)
PyMODINIT_FUNC PyInit_mathutils_kdtree(void)
PyMODINIT_FUNC PyInit_mathutils_noise(void)
bool PyC_IsInterpreterActive(void)
PyObject_HEAD PointerRNA ptr
Definition: bpy_rna.h:125
void * next
Definition: DNA_ID.h:274
char name[66]
Definition: DNA_ID.h:283
void * first
Definition: DNA_listBase.h:47
Definition: BKE_main.h:116
ListBase texts
Definition: BKE_main.h:163
struct StructRNA * type
Definition: RNA_types.h:51
void * data
Definition: RNA_types.h:52
struct ID * owner_id
Definition: RNA_types.h:50
int flags
void * compiled
double PIL_check_seconds_timer(void)
Definition: time.c:80
ccl_device_inline int mod(int x, int m)
Definition: util_math.h:405
#define G(x, y, z)
uint len
PointerRNA * ptr
Definition: wm_files.c:3157