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 * The Original Code is Copyright (C) 2007 Blender Foundation.
17 * All rights reserved.
18 */
19
20 /** \file
21 * \ingroup wm
22 *
23 * Manage initializing resources and correctly shutting down.
24 */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #ifdef _WIN32
31 # define WIN32_LEAN_AND_MEAN
32 # include <windows.h>
33 #endif
34
35 #include "MEM_guardedalloc.h"
36
37 #include "CLG_log.h"
38
39 #include "DNA_genfile.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_userdef_types.h"
42 #include "DNA_windowmanager_types.h"
43
44 #include "BLI_listbase.h"
45 #include "BLI_path_util.h"
46 #include "BLI_string.h"
47 #include "BLI_task.h"
48 #include "BLI_threads.h"
49 #include "BLI_timer.h"
50 #include "BLI_utildefines.h"
51
52 #include "BLO_undofile.h"
53 #include "BLO_writefile.h"
54
55 #include "BKE_blender.h"
56 #include "BKE_blendfile.h"
57 #include "BKE_callbacks.h"
58 #include "BKE_context.h"
59 #include "BKE_font.h"
60 #include "BKE_global.h"
61 #include "BKE_icons.h"
62 #include "BKE_image.h"
63 #include "BKE_keyconfig.h"
64 #include "BKE_lib_remap.h"
65 #include "BKE_main.h"
66 #include "BKE_mball_tessellate.h"
67 #include "BKE_node.h"
68 #include "BKE_report.h"
69 #include "BKE_scene.h"
70 #include "BKE_screen.h"
71 #include "BKE_sound.h"
72
73 #include "BKE_addon.h"
74 #include "BKE_appdir.h"
75 #include "BKE_mask.h" /* free mask clipboard */
76 #include "BKE_material.h" /* BKE_material_copybuf_clear */
77 #include "BKE_sequencer.h" /* free seq clipboard */
78 #include "BKE_studiolight.h"
79 #include "BKE_tracking.h" /* free tracking clipboard */
80
81 #include "RE_engine.h"
82 #include "RE_pipeline.h" /* RE_ free stuff */
83
84 #include "IMB_thumbs.h"
85
86 #ifdef WITH_PYTHON
87 # include "BPY_extern.h"
88 # include "BPY_extern_python.h"
89 # include "BPY_extern_run.h"
90 #endif
91
92 #include "GHOST_C-api.h"
93 #include "GHOST_Path-api.h"
94
95 #include "RNA_define.h"
96
97 #include "WM_api.h"
98 #include "WM_message.h"
99 #include "WM_types.h"
100
101 #include "wm.h"
102 #include "wm_cursors.h"
103 #include "wm_event_system.h"
104 #include "wm_files.h"
105 #include "wm_platform_support.h"
106 #include "wm_surface.h"
107 #include "wm_window.h"
108
109 #include "ED_anim_api.h"
110 #include "ED_armature.h"
111 #include "ED_gpencil.h"
112 #include "ED_keyframes_edit.h"
113 #include "ED_keyframing.h"
114 #include "ED_node.h"
115 #include "ED_render.h"
116 #include "ED_screen.h"
117 #include "ED_space_api.h"
118 #include "ED_undo.h"
119 #include "ED_util.h"
120
121 #include "BLF_api.h"
122 #include "BLT_lang.h"
123 #include "UI_interface.h"
124 #include "UI_resources.h"
125
126 #include "GPU_context.h"
127 #include "GPU_init_exit.h"
128 #include "GPU_material.h"
129
130 #include "BKE_sound.h"
131 #include "BKE_subdiv.h"
132
133 #include "COM_compositor.h"
134
135 #include "DEG_depsgraph.h"
136 #include "DEG_depsgraph_query.h"
137
138 #include "DRW_engine.h"
139
140 CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_OPERATORS, "wm.operator");
141 CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_HANDLERS, "wm.handler");
142 CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_EVENTS, "wm.event");
143 CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_KEYMAPS, "wm.keymap");
144 CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_TOOLS, "wm.tool");
145 CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_MSGBUS_PUB, "wm.msgbus.pub");
146 CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_MSGBUS_SUB, "wm.msgbus.sub");
147
wm_init_reports(bContext * C)148 static void wm_init_reports(bContext *C)
149 {
150 ReportList *reports = CTX_wm_reports(C);
151
152 BLI_assert(!reports || BLI_listbase_is_empty(&reports->list));
153
154 BKE_reports_init(reports, RPT_STORE);
155 }
wm_free_reports(wmWindowManager * wm)156 static void wm_free_reports(wmWindowManager *wm)
157 {
158 BKE_reports_clear(&wm->reports);
159 }
160
161 static bool wm_start_with_console = false;
162
WM_init_state_start_with_console_set(bool value)163 void WM_init_state_start_with_console_set(bool value)
164 {
165 wm_start_with_console = value;
166 }
167
168 /**
169 * Since we cannot know in advance if we will require the draw manager
170 * context when starting blender in background mode (specially true with
171 * scripts) we defer the ghost initialization the most as possible
172 * so that it does not break anything that can run in headless mode (as in
173 * without display server attached).
174 */
175 static bool opengl_is_init = false;
176
WM_init_opengl(void)177 void WM_init_opengl(void)
178 {
179 /* must be called only once */
180 BLI_assert(opengl_is_init == false);
181
182 if (G.background) {
183 /* Ghost is still not init elsewhere in background mode. */
184 wm_ghost_init(NULL);
185 }
186
187 /* Needs to be first to have an ogl context bound. */
188 DRW_opengl_context_create();
189
190 GPU_init();
191
192 GPU_pass_cache_init();
193
194 opengl_is_init = true;
195 }
196
sound_jack_sync_callback(Main * bmain,int mode,double time)197 static void sound_jack_sync_callback(Main *bmain, int mode, double time)
198 {
199 /* Ugly: Blender doesn't like it when the animation is played back during rendering. */
200 if (G.is_rendering) {
201 return;
202 }
203
204 wmWindowManager *wm = bmain->wm.first;
205
206 LISTBASE_FOREACH (wmWindow *, window, &wm->windows) {
207 Scene *scene = WM_window_get_active_scene(window);
208 if ((scene->audio.flag & AUDIO_SYNC) == 0) {
209 continue;
210 }
211 ViewLayer *view_layer = WM_window_get_active_view_layer(window);
212 Depsgraph *depsgraph = BKE_scene_get_depsgraph(scene, view_layer);
213 if (depsgraph == NULL) {
214 continue;
215 }
216 BKE_sound_lock();
217 Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
218 BKE_sound_jack_scene_update(scene_eval, mode, time);
219 BKE_sound_unlock();
220 }
221 }
222
223 /* only called once, for startup */
WM_init(bContext * C,int argc,const char ** argv)224 void WM_init(bContext *C, int argc, const char **argv)
225 {
226
227 if (!G.background) {
228 wm_ghost_init(C); /* note: it assigns C to ghost! */
229 wm_init_cursor_data();
230 BKE_sound_jack_sync_callback_set(sound_jack_sync_callback);
231 }
232
233 GHOST_CreateSystemPaths();
234
235 BKE_addon_pref_type_init();
236 BKE_keyconfig_pref_type_init();
237
238 wm_operatortype_init();
239 wm_operatortypes_register();
240
241 WM_paneltype_init(); /* Lookup table only. */
242 WM_menutype_init();
243 WM_uilisttype_init();
244 wm_gizmotype_init();
245 wm_gizmogrouptype_init();
246
247 ED_undosys_type_init();
248
249 BKE_library_callback_free_notifier_reference_set(
250 WM_main_remove_notifier_reference); /* lib_id.c */
251 BKE_region_callback_free_gizmomap_set(wm_gizmomap_remove); /* screen.c */
252 BKE_region_callback_refresh_tag_gizmomap_set(WM_gizmomap_tag_refresh);
253 BKE_library_callback_remap_editor_id_reference_set(
254 WM_main_remap_editor_id_reference); /* lib_id.c */
255 BKE_spacedata_callback_id_remap_set(ED_spacedata_id_remap); /* screen.c */
256 DEG_editors_set_update_cb(ED_render_id_flush_update, ED_render_scene_update);
257
258 ED_spacetypes_init(); /* editors/space_api/spacetype.c */
259
260 ED_node_init_butfuncs();
261
262 BLF_init();
263
264 BLT_lang_init();
265 /* Must call first before doing any '.blend' file reading,
266 * since versioning code may create new IDs... See T57066. */
267 BLT_lang_set(NULL);
268
269 /* Init icons before reading .blend files for preview icons, which can
270 * get triggered by the depsgraph. This is also done in background mode
271 * for scripts that do background processing with preview icons. */
272 BKE_icons_init(BIFICONID_LAST);
273
274 /* reports cant be initialized before the wm,
275 * but keep before file reading, since that may report errors */
276 wm_init_reports(C);
277
278 WM_msgbus_types_init();
279
280 /* get the default database, plus a wm */
281 bool is_factory_startup = true;
282 const bool use_data = true;
283 const bool use_userdef = true;
284
285 /* Studio-lights needs to be init before we read the home-file,
286 * otherwise the versioning cannot find the default studio-light. */
287 BKE_studiolight_init();
288
289 BLI_assert((G.fileflags & G_FILE_NO_UI) == 0);
290
291 wm_homefile_read(C,
292 NULL,
293 G.factory_startup,
294 false,
295 use_data,
296 use_userdef,
297 NULL,
298 WM_init_state_app_template_get(),
299 &is_factory_startup);
300
301 /* Call again to set from userpreferences... */
302 BLT_lang_set(NULL);
303
304 /* For fsMenu. Called here so can include user preference paths if needed. */
305 ED_file_init();
306
307 /* That one is generated on demand, we need to be sure it's clear on init. */
308 IMB_thumb_clear_translations();
309
310 if (!G.background) {
311
312 #ifdef WITH_INPUT_NDOF
313 /* sets 3D mouse deadzone */
314 WM_ndof_deadzone_set(U.ndof_deadzone);
315 #endif
316 WM_init_opengl();
317
318 if (!WM_platform_support_perform_checks()) {
319 exit(-1);
320 }
321
322 UI_init();
323 }
324
325 BKE_subdiv_init();
326
327 ED_spacemacros_init();
328
329 /* note: there is a bug where python needs initializing before loading the
330 * startup.blend because it may contain PyDrivers. It also needs to be after
331 * initializing space types and other internal data.
332 *
333 * However cant redo this at the moment. Solution is to load python
334 * before wm_homefile_read() or make py-drivers check if python is running.
335 * Will try fix when the crash can be repeated. - campbell. */
336
337 #ifdef WITH_PYTHON
338 BPY_python_start(C, argc, argv);
339 BPY_python_reset(C);
340 #else
341 (void)argc; /* unused */
342 (void)argv; /* unused */
343 #endif
344
345 if (!G.background && !wm_start_with_console) {
346 GHOST_toggleConsole(3);
347 }
348
349 BKE_material_copybuf_clear();
350 ED_render_clear_mtex_copybuf();
351
352 wm_history_file_read();
353
354 /* allow a path of "", this is what happens when making a new file */
355 #if 0
356 if (BKE_main_blendfile_path_from_global()[0] == '\0') {
357 BLI_join_dirfile(
358 G_MAIN->name, sizeof(G_MAIN->name), BKE_appdir_folder_default(), "untitled.blend");
359 }
360 #endif
361
362 BLI_strncpy(G.lib, BKE_main_blendfile_path_from_global(), sizeof(G.lib));
363
364 #ifdef WITH_COMPOSITOR
365 if (1) {
366 extern void *COM_linker_hack;
367 COM_linker_hack = COM_execute;
368 }
369 #endif
370
371 {
372 Main *bmain = CTX_data_main(C);
373 /* note, logic here is from wm_file_read_post,
374 * call functions that depend on Python being initialized. */
375
376 /* normally 'wm_homefile_read' will do this,
377 * however python is not initialized when called from this function.
378 *
379 * unlikely any handlers are set but its possible,
380 * note that recovering the last session does its own callbacks. */
381 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
382
383 BKE_callback_exec_null(bmain, BKE_CB_EVT_VERSION_UPDATE);
384 BKE_callback_exec_null(bmain, BKE_CB_EVT_LOAD_POST);
385 if (is_factory_startup) {
386 BKE_callback_exec_null(bmain, BKE_CB_EVT_LOAD_FACTORY_STARTUP_POST);
387 }
388
389 wm_file_read_report(C, bmain);
390
391 if (!G.background) {
392 CTX_wm_window_set(C, NULL);
393 }
394 }
395 }
396
WM_init_splash(bContext * C)397 void WM_init_splash(bContext *C)
398 {
399 if ((U.uiflag & USER_SPLASH_DISABLE) == 0) {
400 wmWindowManager *wm = CTX_wm_manager(C);
401 wmWindow *prevwin = CTX_wm_window(C);
402
403 if (wm->windows.first) {
404 CTX_wm_window_set(C, wm->windows.first);
405 WM_operator_name_call(C, "WM_OT_splash", WM_OP_INVOKE_DEFAULT, NULL);
406 CTX_wm_window_set(C, prevwin);
407 }
408 }
409 }
410
411 /* free strings of open recent files */
free_openrecent(void)412 static void free_openrecent(void)
413 {
414 struct RecentFile *recent;
415
416 for (recent = G.recent_files.first; recent; recent = recent->next) {
417 MEM_freeN(recent->filepath);
418 }
419
420 BLI_freelistN(&(G.recent_files));
421 }
422
423 #ifdef WIN32
424 /* Read console events until there is a key event. Also returns on any error. */
wait_for_console_key(void)425 static void wait_for_console_key(void)
426 {
427 HANDLE hConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
428
429 if (!ELEM(hConsoleInput, NULL, INVALID_HANDLE_VALUE) && FlushConsoleInputBuffer(hConsoleInput)) {
430 for (;;) {
431 INPUT_RECORD buffer;
432 DWORD ignored;
433
434 if (!ReadConsoleInput(hConsoleInput, &buffer, 1, &ignored)) {
435 break;
436 }
437
438 if (buffer.EventType == KEY_EVENT) {
439 break;
440 }
441 }
442 }
443 }
444 #endif
445
wm_exit_handler(bContext * C,const wmEvent * event,void * userdata)446 static int wm_exit_handler(bContext *C, const wmEvent *event, void *userdata)
447 {
448 WM_exit(C);
449
450 UNUSED_VARS(event, userdata);
451 return WM_UI_HANDLER_BREAK;
452 }
453
454 /**
455 * Cause a delayed #WM_exit()
456 * call to avoid leaking memory when trying to exit from within operators.
457 */
wm_exit_schedule_delayed(const bContext * C)458 void wm_exit_schedule_delayed(const bContext *C)
459 {
460 /* What we do here is a little bit hacky, but quite simple and doesn't require bigger
461 * changes: Add a handler wrapping WM_exit() to cause a delayed call of it. */
462
463 wmWindow *win = CTX_wm_window(C);
464
465 /* Use modal UI handler for now.
466 * Could add separate WM handlers or so, but probably not worth it. */
467 WM_event_add_ui_handler(C, &win->modalhandlers, wm_exit_handler, NULL, NULL, 0);
468 WM_event_add_mousemove(win); /* ensure handler actually gets called */
469 }
470
471 /**
472 * \note doesn't run exit() call #WM_exit() for that.
473 */
WM_exit_ex(bContext * C,const bool do_python)474 void WM_exit_ex(bContext *C, const bool do_python)
475 {
476 wmWindowManager *wm = C ? CTX_wm_manager(C) : NULL;
477
478 /* first wrap up running stuff, we assume only the active WM is running */
479 /* modal handlers are on window level freed, others too? */
480 /* note; same code copied in wm_files.c */
481 if (C && wm) {
482 if (!G.background) {
483 struct MemFile *undo_memfile = wm->undo_stack ?
484 ED_undosys_stack_memfile_get_active(wm->undo_stack) :
485 NULL;
486 if (undo_memfile != NULL) {
487 /* save the undo state as quit.blend */
488 Main *bmain = CTX_data_main(C);
489 char filename[FILE_MAX];
490 bool has_edited;
491 const int fileflags = G.fileflags & ~G_FILE_COMPRESS;
492
493 BLI_join_dirfile(filename, sizeof(filename), BKE_tempdir_base(), BLENDER_QUIT_FILE);
494
495 has_edited = ED_editors_flush_edits(bmain);
496
497 if ((has_edited &&
498 BLO_write_file(
499 bmain, filename, fileflags, &(const struct BlendFileWriteParams){0}, NULL)) ||
500 (undo_memfile && BLO_memfile_write_file(undo_memfile, filename))) {
501 printf("Saved session recovery to '%s'\n", filename);
502 }
503 }
504 }
505
506 WM_jobs_kill_all(wm);
507
508 LISTBASE_FOREACH (wmWindow *, win, &wm->windows) {
509 CTX_wm_window_set(C, win); /* needed by operator close callbacks */
510 WM_event_remove_handlers(C, &win->handlers);
511 WM_event_remove_handlers(C, &win->modalhandlers);
512 ED_screen_exit(C, win, WM_window_get_active_screen(win));
513 }
514
515 if (!G.background) {
516 if ((U.pref_flag & USER_PREF_FLAG_SAVE) && ((G.f & G_FLAG_USERPREF_NO_SAVE_ON_EXIT) == 0)) {
517 if (U.runtime.is_dirty) {
518 BKE_blendfile_userdef_write_all(NULL);
519 }
520 }
521 }
522 }
523
524 #ifdef WITH_PYTHON
525 /* Without this, we there isn't a good way to manage false-positive resource leaks
526 * where a #PyObject references memory allocated with guarded-alloc, T71362.
527 *
528 * This allows add-ons to free resources when unregistered (which is good practice anyway). */
529 BPY_run_string_eval(C, (const char *[]){"addon_utils", NULL}, "addon_utils.disable_all()");
530 #endif
531
532 BLI_timer_free();
533
534 WM_paneltype_clear();
535
536 BKE_addon_pref_type_free();
537 BKE_keyconfig_pref_type_free();
538 BKE_materials_exit();
539
540 wm_operatortype_free();
541 wm_surfaces_free();
542 wm_dropbox_free();
543 WM_menutype_free();
544 WM_uilisttype_free();
545
546 /* all non-screen and non-space stuff editors did, like editmode */
547 if (C) {
548 Main *bmain = CTX_data_main(C);
549 ED_editors_exit(bmain, true);
550 }
551
552 ED_undosys_type_free();
553
554 free_openrecent();
555
556 BKE_mball_cubeTable_free();
557
558 /* render code might still access databases */
559 RE_FreeAllRender();
560 RE_engines_exit();
561
562 ED_preview_free_dbase(); /* frees a Main dbase, before BKE_blender_free! */
563
564 if (wm) {
565 /* Before BKE_blender_free! - since the ListBases get freed there. */
566 wm_free_reports(wm);
567 }
568
569 BKE_sequencer_free_clipboard(); /* sequencer.c */
570 BKE_tracking_clipboard_free();
571 BKE_mask_clipboard_free();
572 BKE_vfont_clipboard_free();
573 BKE_node_clipboard_free();
574
575 #ifdef WITH_COMPOSITOR
576 COM_deinitialize();
577 #endif
578
579 BKE_subdiv_exit();
580
581 if (opengl_is_init) {
582 BKE_image_free_unused_gpu_textures();
583 }
584
585 BKE_blender_free(); /* blender.c, does entire library and spacetypes */
586 // BKE_material_copybuf_free();
587 ANIM_fcurves_copybuf_free();
588 ANIM_drivers_copybuf_free();
589 ANIM_driver_vars_copybuf_free();
590 ANIM_fmodifiers_copybuf_free();
591 ED_gpencil_anim_copybuf_free();
592 ED_gpencil_strokes_copybuf_free();
593
594 /* free gizmo-maps after freeing blender,
595 * so no deleted data get accessed during cleaning up of areas. */
596 wm_gizmomaptypes_free();
597 wm_gizmogrouptype_free();
598 wm_gizmotype_free();
599
600 BLF_exit();
601
602 if (opengl_is_init) {
603 DRW_opengl_context_enable_ex(false);
604 GPU_pass_cache_free();
605 GPU_exit();
606 DRW_opengl_context_disable_ex(false);
607 DRW_opengl_context_destroy();
608 }
609
610 #ifdef WITH_INTERNATIONAL
611 BLT_lang_free();
612 #endif
613
614 ANIM_keyingset_infos_exit();
615
616 // free_txt_data();
617
618 #ifdef WITH_PYTHON
619 /* option not to close python so we can use 'atexit' */
620 if (do_python && ((C == NULL) || CTX_py_init_get(C))) {
621 /* XXX - old note */
622 /* before BKE_blender_free so py's gc happens while library still exists */
623 /* needed at least for a rare sigsegv that can happen in pydrivers */
624
625 /* Update for blender 2.5, move after BKE_blender_free because Blender now holds references to
626 * PyObject's so decref'ing them after python ends causes bad problems every time
627 * the py-driver bug can be fixed if it happens again we can deal with it then. */
628 BPY_python_end();
629 }
630 #else
631 (void)do_python;
632 #endif
633
634 ED_file_exit(); /* for fsmenu */
635
636 UI_exit();
637 BKE_blender_userdef_data_free(&U, false);
638
639 RNA_exit(); /* should be after BPY_python_end so struct python slots are cleared */
640
641 GPU_backend_exit();
642
643 wm_ghost_exit();
644
645 CTX_free(C);
646
647 GHOST_DisposeSystemPaths();
648
649 DNA_sdna_current_free();
650
651 BLI_threadapi_exit();
652 BLI_task_scheduler_exit();
653
654 /* No need to call this early, rather do it late so that other
655 * pieces of Blender using sound may exit cleanly, see also T50676. */
656 BKE_sound_exit();
657
658 CLG_exit();
659
660 BKE_blender_atexit();
661
662 wm_autosave_delete();
663
664 BKE_tempdir_session_purge();
665 }
666
667 /**
668 * \brief Main exit function to close Blender ordinarily.
669 * \note Use #wm_exit_schedule_delayed() to close Blender from an operator.
670 * Might leak memory otherwise.
671 */
WM_exit(bContext * C)672 void WM_exit(bContext *C)
673 {
674 WM_exit_ex(C, true);
675
676 printf("\nBlender quit\n");
677
678 #ifdef WIN32
679 /* ask user to press a key when in debug mode */
680 if (G.debug & G_DEBUG) {
681 printf("Press any key to exit . . .\n\n");
682 wait_for_console_key();
683 }
684 #endif
685
686 exit(G.is_break == true);
687 }
688
689 /**
690 * Needed for cases when operators are re-registered
691 * (when operator type pointers are stored).
692 */
WM_script_tag_reload(void)693 void WM_script_tag_reload(void)
694 {
695 UI_interface_tag_script_reload();
696 }
697