Merge branch 'master' into blender2.8
[blender.git] / source / blender / windowmanager / intern / wm_init_exit.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_init_exit.c
28  *  \ingroup wm
29  *
30  * Manage initializing resources and correctly shutting down.
31  */
32
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36
37 #ifdef WIN32
38 #  include <windows.h>
39 #endif
40
41 #include "MEM_guardedalloc.h"
42
43 #include "DNA_genfile.h"
44 #include "DNA_scene_types.h"
45 #include "DNA_userdef_types.h"
46 #include "DNA_windowmanager_types.h"
47
48 #include "BLI_callbacks.h"
49 #include "BLI_listbase.h"
50 #include "BLI_path_util.h"
51 #include "BLI_string.h"
52 #include "BLI_threads.h"
53 #include "BLI_utildefines.h"
54
55 #include "BLO_writefile.h"
56
57 #include "BKE_blender.h"
58 #include "BKE_blender_undo.h"
59 #include "BKE_context.h"
60 #include "BKE_screen.h"
61 #include "BKE_DerivedMesh.h"
62 #include "BKE_global.h"
63 #include "BKE_icons.h"
64 #include "BKE_library.h"
65 #include "BKE_library_remap.h"
66 #include "BKE_main.h"
67 #include "BKE_mball_tessellate.h"
68 #include "BKE_node.h"
69 #include "BKE_report.h"
70 #include "BKE_font.h"
71
72 #include "BKE_addon.h"
73 #include "BKE_appdir.h"
74 #include "BKE_sequencer.h" /* free seq clipboard */
75 #include "BKE_material.h" /* clear_matcopybuf */
76 #include "BKE_tracking.h" /* free tracking clipboard */
77 #include "BKE_mask.h" /* free mask clipboard */
78
79 #include "RE_engine.h"
80 #include "RE_pipeline.h"        /* RE_ free stuff */
81
82 #ifdef WITH_PYTHON
83 #include "BPY_extern.h"
84 #endif
85
86 #ifdef WITH_GAMEENGINE
87 #  include "BL_System.h"
88 #endif
89 #include "GHOST_Path-api.h"
90 #include "GHOST_C-api.h"
91
92 #include "RNA_define.h"
93
94 #include "WM_api.h"
95 #include "WM_types.h"
96
97 #include "wm_cursors.h"
98 #include "wm_event_system.h"
99 #include "wm.h"
100 #include "wm_files.h"
101 #include "wm_window.h"
102
103 #include "ED_anim_api.h"
104 #include "ED_armature.h"
105 #include "ED_gpencil.h"
106 #include "ED_keyframing.h"
107 #include "ED_keyframes_edit.h"
108 #include "ED_node.h"
109 #include "ED_render.h"
110 #include "ED_space_api.h"
111 #include "ED_screen.h"
112 #include "ED_util.h"
113
114 #include "UI_interface.h"
115 #include "BLF_api.h"
116 #include "BLT_lang.h"
117
118 #include "GPU_buffers.h"
119 #include "GPU_draw.h"
120 #include "GPU_init_exit.h"
121
122 #include "BKE_sound.h"
123 #include "COM_compositor.h"
124
125 #include "DEG_depsgraph.h"
126
127 #ifdef WITH_OPENSUBDIV
128 #  include "BKE_subsurf.h"
129 #endif
130
131 static void wm_init_reports(bContext *C)
132 {
133         ReportList *reports = CTX_wm_reports(C);
134
135         BLI_assert(!reports || BLI_listbase_is_empty(&reports->list));
136
137         BKE_reports_init(reports, RPT_STORE);
138 }
139 static void wm_free_reports(bContext *C)
140 {
141         ReportList *reports = CTX_wm_reports(C);
142
143         BKE_reports_clear(reports);
144 }
145
146 static void wm_undo_kill_callback(bContext *C)
147 {
148         WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
149 }
150
151 bool wm_start_with_console = false; /* used in creator.c */
152
153 /* only called once, for startup */
154 void WM_init(bContext *C, int argc, const char **argv)
155 {
156         
157         if (!G.background) {
158                 wm_ghost_init(C);   /* note: it assigns C to ghost! */
159                 wm_init_cursor_data();
160         }
161         GHOST_CreateSystemPaths();
162
163         BKE_addon_pref_type_init();
164
165         wm_operatortype_init();
166         WM_menutype_init();
167         WM_uilisttype_init();
168         wm_manipulatortype_init();
169         wm_manipulatorgrouptype_init();
170
171         BKE_undo_callback_wm_kill_jobs_set(wm_undo_kill_callback);
172
173         BKE_library_callback_free_window_manager_set(wm_close_and_free);   /* library.c */
174         BKE_library_callback_free_notifier_reference_set(WM_main_remove_notifier_reference);   /* library.c */
175         BKE_region_callback_free_manipulatormap_set(wm_manipulatormap_remove); /* screen.c */
176         BKE_region_callback_refresh_tag_manipulatormap_set(WM_manipulatormap_tag_refresh);
177         BKE_library_callback_remap_editor_id_reference_set(WM_main_remap_editor_id_reference);   /* library.c */
178         BKE_blender_callback_test_break_set(wm_window_testbreak); /* blender.c */
179         BKE_spacedata_callback_id_remap_set(ED_spacedata_id_remap); /* screen.c */
180         DEG_editors_set_update_cb(ED_render_id_flush_update,
181                                   ED_render_scene_update,
182                                   ED_render_scene_update_pre);
183         
184         ED_spacetypes_init();   /* editors/space_api/spacetype.c */
185         
186         ED_file_init();         /* for fsmenu */
187         ED_node_init_butfuncs();
188         
189         BLF_init(); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */
190         BLT_lang_init();
191
192         /* reports cant be initialized before the wm,
193          * but keep before file reading, since that may report errors */
194         wm_init_reports(C);
195
196         /* get the default database, plus a wm */
197         wm_homefile_read(C, NULL, G.factory_startup, false, true, NULL, NULL);
198         
199
200         BLT_lang_set(NULL);
201
202         if (!G.background) {
203
204 #ifdef WITH_INPUT_NDOF
205                 /* sets 3D mouse deadzone */
206                 WM_ndof_deadzone_set(U.ndof_deadzone);
207 #endif
208
209                 GPU_init();
210
211                 GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP));
212                 GPU_set_linear_mipmap(true);
213                 GPU_set_anisotropic(U.anisotropic_filter);
214                 GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
215
216 #ifdef WITH_OPENSUBDIV
217                 BKE_subsurf_osd_init();
218 #endif
219
220                 UI_init();
221         }
222         else {
223                 /* Note: Currently only inits icons, which we now want in background mode too
224                  * (scripts could use those in background processing...).
225                  * In case we do more later, we may need to pass a 'background' flag.
226                  * Called from 'UI_init' above */
227                 BKE_icons_init(1);
228         }
229
230
231         ED_spacemacros_init();
232
233         /* note: there is a bug where python needs initializing before loading the
234          * startup.blend because it may contain PyDrivers. It also needs to be after
235          * initializing space types and other internal data.
236          *
237          * However cant redo this at the moment. Solution is to load python
238          * before wm_homefile_read() or make py-drivers check if python is running.
239          * Will try fix when the crash can be repeated. - campbell. */
240
241 #ifdef WITH_PYTHON
242         BPY_context_set(C); /* necessary evil */
243         BPY_python_start(argc, argv);
244
245         BPY_python_reset(C);
246 #else
247         (void)argc; /* unused */
248         (void)argv; /* unused */
249 #endif
250
251         if (!G.background && !wm_start_with_console)
252                 GHOST_toggleConsole(3);
253
254         clear_matcopybuf();
255         ED_render_clear_mtex_copybuf();
256
257         // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
258
259         wm_history_file_read();
260
261         /* allow a path of "", this is what happens when making a new file */
262 #if 0
263         if (G.main->name[0] == 0)
264                 BLI_make_file_string("/", G.main->name, BKE_appdir_folder_default(), "untitled.blend");
265 #endif
266
267         BLI_strncpy(G.lib, G.main->name, FILE_MAX);
268
269 #ifdef WITH_COMPOSITOR
270         if (1) {
271                 extern void *COM_linker_hack;
272                 COM_linker_hack = COM_execute;
273         }
274 #endif
275         
276         /* load last session, uses regular file reading so it has to be in end (after init py etc) */
277         if (U.uiflag2 & USER_KEEP_SESSION) {
278                 /* calling WM_recover_last_session(C, NULL) has been moved to creator.c */
279                 /* that prevents loading both the kept session, and the file on the command line */
280         }
281         else {
282                 /* note, logic here is from wm_file_read_post,
283                  * call functions that depend on Python being initialized. */
284
285                 /* normally 'wm_homefile_read' will do this,
286                  * however python is not initialized when called from this function.
287                  *
288                  * unlikely any handlers are set but its possible,
289                  * note that recovering the last session does its own callbacks. */
290                 CTX_wm_window_set(C, CTX_wm_manager(C)->windows.first);
291
292                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_VERSION_UPDATE);
293                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
294
295                 wm_file_read_report(C);
296
297                 if (!G.background) {
298                         CTX_wm_window_set(C, NULL);
299                 }
300         }
301 }
302
303 void WM_init_splash(bContext *C)
304 {
305         if ((U.uiflag & USER_SPLASH_DISABLE) == 0) {
306                 wmWindowManager *wm = CTX_wm_manager(C);
307                 wmWindow *prevwin = CTX_wm_window(C);
308         
309                 if (wm->windows.first) {
310                         CTX_wm_window_set(C, wm->windows.first);
311                         WM_operator_name_call(C, "WM_OT_splash", WM_OP_INVOKE_DEFAULT, NULL);
312                         CTX_wm_window_set(C, prevwin);
313                 }
314         }
315 }
316
317 bool WM_init_game(bContext *C)
318 {
319         wmWindowManager *wm = CTX_wm_manager(C);
320         wmWindow *win;
321
322         ScrArea *sa;
323         ARegion *ar = NULL;
324
325         Scene *scene = CTX_data_scene(C);
326
327         if (!scene) {
328                 /* XXX, this should not be needed. */
329                 Main *bmain = CTX_data_main(C);
330                 scene = bmain->scene.first;
331         }
332
333         win = wm->windows.first;
334
335         /* first to get a valid window */
336         if (win)
337                 CTX_wm_window_set(C, win);
338
339         sa = BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_VIEW3D, 0);
340         ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
341
342         /* if we have a valid 3D view */
343         if (sa && ar) {
344                 ARegion *arhide;
345
346                 CTX_wm_area_set(C, sa);
347                 CTX_wm_region_set(C, ar);
348
349                 /* disable quad view */
350                 if (ar->alignment == RGN_ALIGN_QSPLIT)
351                         WM_operator_name_call(C, "SCREEN_OT_region_quadview", WM_OP_EXEC_DEFAULT, NULL);
352
353                 /* toolbox, properties panel and header are hidden */
354                 for (arhide = sa->regionbase.first; arhide; arhide = arhide->next) {
355                         if (arhide->regiontype != RGN_TYPE_WINDOW) {
356                                 if (!(arhide->flag & RGN_FLAG_HIDDEN)) {
357                                         ED_region_toggle_hidden(C, arhide);
358                                 }
359                         }
360                 }
361
362                 /* full screen the area */
363                 if (!sa->full) {
364                         ED_screen_state_toggle(C, win, sa, SCREENMAXIMIZED);
365                 }
366
367                 /* Fullscreen */
368                 if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) {
369                         WM_operator_name_call(C, "WM_OT_window_fullscreen_toggle", WM_OP_EXEC_DEFAULT, NULL);
370                         wm_get_screensize(&ar->winrct.xmax, &ar->winrct.ymax);
371                         ar->winx = ar->winrct.xmax + 1;
372                         ar->winy = ar->winrct.ymax + 1;
373                 }
374                 else {
375                         GHOST_RectangleHandle rect = GHOST_GetClientBounds(win->ghostwin);
376                         ar->winrct.ymax = GHOST_GetHeightRectangle(rect);
377                         ar->winrct.xmax = GHOST_GetWidthRectangle(rect);
378                         ar->winx = ar->winrct.xmax + 1;
379                         ar->winy = ar->winrct.ymax + 1;
380                         GHOST_DisposeRectangle(rect);
381                 }
382
383                 WM_operator_name_call(C, "VIEW3D_OT_game_start", WM_OP_EXEC_DEFAULT, NULL);
384
385                 BKE_sound_exit();
386
387                 return true;
388         }
389         else {
390                 ReportTimerInfo *rti;
391
392                 BKE_report(&wm->reports, RPT_ERROR, "No valid 3D View found, game auto start is not possible");
393
394                 /* After adding the report to the global list, reset the report timer. */
395                 WM_event_remove_timer(wm, NULL, wm->reports.reporttimer);
396
397                 /* Records time since last report was added */
398                 wm->reports.reporttimer = WM_event_add_timer(wm, CTX_wm_window(C), TIMER, 0.02);
399
400                 rti = MEM_callocN(sizeof(ReportTimerInfo), "ReportTimerInfo");
401                 wm->reports.reporttimer->customdata = rti;
402
403                 return false;
404         }
405 }
406
407 /* free strings of open recent files */
408 static void free_openrecent(void)
409 {
410         struct RecentFile *recent;
411         
412         for (recent = G.recent_files.first; recent; recent = recent->next)
413                 MEM_freeN(recent->filepath);
414         
415         BLI_freelistN(&(G.recent_files));
416 }
417
418
419 #ifdef WIN32
420 /* Read console events until there is a key event.  Also returns on any error. */
421 static void wait_for_console_key(void)
422 {
423         HANDLE hConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
424
425         if (!ELEM(hConsoleInput, NULL, INVALID_HANDLE_VALUE) && FlushConsoleInputBuffer(hConsoleInput)) {
426                 for (;;) {
427                         INPUT_RECORD buffer;
428                         DWORD ignored;
429
430                         if (!ReadConsoleInput(hConsoleInput, &buffer, 1, &ignored)) {
431                                 break;
432                         }
433
434                         if (buffer.EventType == KEY_EVENT) {
435                                 break;
436                         }
437                 }
438         }
439 }
440 #endif
441
442 /**
443  * \note doesn't run exit() call #WM_exit() for that.
444  */
445 void WM_exit_ext(bContext *C, const bool do_python)
446 {
447         wmWindowManager *wm = C ? CTX_wm_manager(C) : NULL;
448
449         /* first wrap up running stuff, we assume only the active WM is running */
450         /* modal handlers are on window level freed, others too? */
451         /* note; same code copied in wm_files.c */
452         if (C && wm) {
453                 wmWindow *win;
454
455                 if (!G.background) {
456                         if ((U.uiflag2 & USER_KEEP_SESSION) || BKE_undo_is_valid(NULL)) {
457                                 /* save the undo state as quit.blend */
458                                 char filename[FILE_MAX];
459                                 bool has_edited;
460                                 int fileflags = G.fileflags & ~(G_FILE_COMPRESS | G_FILE_AUTOPLAY | G_FILE_HISTORY);
461
462                                 BLI_make_file_string("/", filename, BKE_tempdir_base(), BLENDER_QUIT_FILE);
463
464                                 has_edited = ED_editors_flush_edits(C, false);
465
466                                 if ((has_edited && BLO_write_file(CTX_data_main(C), filename, fileflags, NULL, NULL)) ||
467                                     BKE_undo_save_file(filename))
468                                 {
469                                         printf("Saved session recovery to '%s'\n", filename);
470                                 }
471                         }
472                 }
473                 
474                 WM_jobs_kill_all(wm);
475
476                 for (win = wm->windows.first; win; win = win->next) {
477                         
478                         CTX_wm_window_set(C, win);  /* needed by operator close callbacks */
479                         WM_event_remove_handlers(C, &win->handlers);
480                         WM_event_remove_handlers(C, &win->modalhandlers);
481                         ED_screen_exit(C, win, WM_window_get_active_screen(win));
482                 }
483         }
484
485         BKE_addon_pref_type_free();
486         wm_operatortype_free();
487         wm_dropbox_free();
488         WM_menutype_free();
489         WM_uilisttype_free();
490         
491         /* all non-screen and non-space stuff editors did, like editmode */
492         if (C)
493                 ED_editors_exit(C);
494
495 //      XXX     
496 //      BIF_GlobalReebFree();
497 //      BIF_freeRetarget();
498         BIF_freeTemplates(C);
499
500         free_openrecent();
501         
502         BKE_mball_cubeTable_free();
503         
504         /* render code might still access databases */
505         RE_FreeAllRender();
506         RE_engines_exit();
507         
508         ED_preview_free_dbase();  /* frees a Main dbase, before BKE_blender_free! */
509
510         if (C && wm)
511                 wm_free_reports(C);  /* before BKE_blender_free! - since the ListBases get freed there */
512
513         BKE_sequencer_free_clipboard(); /* sequencer.c */
514         BKE_tracking_clipboard_free();
515         BKE_mask_clipboard_free();
516         BKE_vfont_clipboard_free();
517                 
518 #ifdef WITH_COMPOSITOR
519         COM_deinitialize();
520 #endif
521         
522         BKE_blender_free();  /* blender.c, does entire library and spacetypes */
523 //      free_matcopybuf();
524         ANIM_fcurves_copybuf_free();
525         ANIM_drivers_copybuf_free();
526         ANIM_driver_vars_copybuf_free();
527         ANIM_fmodifiers_copybuf_free();
528         ED_gpencil_anim_copybuf_free();
529         ED_gpencil_strokes_copybuf_free();
530         BKE_node_clipboard_clear();
531
532         /* free manipulator-maps after freeing blender, so no deleted data get accessed during cleaning up of areas */
533         wm_manipulatormaptypes_free();
534         wm_manipulatorgrouptype_free();
535         wm_manipulatortype_free();
536
537         BLF_exit();
538
539 #ifdef WITH_INTERNATIONAL
540         BLF_free_unifont();
541         BLF_free_unifont_mono();
542         BLT_lang_free();
543 #endif
544         
545         ANIM_keyingset_infos_exit();
546         
547 //      free_txt_data();
548         
549
550 #ifdef WITH_PYTHON
551         /* option not to close python so we can use 'atexit' */
552         if (do_python && ((C == NULL) || CTX_py_init_get(C))) {
553                 /* XXX - old note */
554                 /* before BKE_blender_free so py's gc happens while library still exists */
555                 /* needed at least for a rare sigsegv that can happen in pydrivers */
556
557                 /* Update for blender 2.5, move after BKE_blender_free because blender now holds references to PyObject's
558                  * so decref'ing them after python ends causes bad problems every time
559                  * the pyDriver bug can be fixed if it happens again we can deal with it then */
560                 BPY_python_end();
561         }
562 #else
563         (void)do_python;
564 #endif
565
566         if (!G.background) {
567 #ifdef WITH_OPENSUBDIV
568                 BKE_subsurf_osd_cleanup();
569 #endif
570
571                 GPU_global_buffer_pool_free();
572                 GPU_free_unused_buffers();
573
574                 GPU_exit();
575         }
576
577         BKE_undo_reset();
578         
579         ED_file_exit(); /* for fsmenu */
580
581         UI_exit();
582         BKE_blender_userdef_data_free(&U, false);
583
584         RNA_exit(); /* should be after BPY_python_end so struct python slots are cleared */
585         
586         wm_ghost_exit();
587
588         CTX_free(C);
589 #ifdef WITH_GAMEENGINE
590         SYS_DeleteSystem(SYS_GetSystem());
591 #endif
592         
593         GHOST_DisposeSystemPaths();
594
595         DNA_sdna_current_free();
596
597         BLI_threadapi_exit();
598
599         /* No need to call this early, rather do it late so that other pieces of Blender using sound may exit cleanly,
600          * see also T50676. */
601         BKE_sound_exit();
602
603         BKE_blender_atexit();
604
605         if (MEM_get_memory_blocks_in_use() != 0) {
606                 size_t mem_in_use = MEM_get_memory_in_use() + MEM_get_memory_in_use();
607                 printf("Error: Not freed memory blocks: %u, total unfreed memory %f MB\n",
608                        MEM_get_memory_blocks_in_use(),
609                        (double)mem_in_use / 1024 / 1024);
610                 MEM_printmemlist();
611         }
612         wm_autosave_delete();
613
614         BKE_tempdir_session_purge();
615 }
616
617 void WM_exit(bContext *C)
618 {
619         WM_exit_ext(C, 1);
620
621         printf("\nBlender quit\n");
622
623 #ifdef WIN32
624         /* ask user to press a key when in debug mode */
625         if (G.debug & G_DEBUG) {
626                 printf("Press any key to exit . . .\n\n");
627                 wait_for_console_key();
628         }
629 #endif
630
631         exit(G.is_break == true);
632 }