fix [#28672] Blender segfault after exiting a game that was opened with
[blender.git] / source / blender / windowmanager / intern / wm_init_exit.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2007 Blender Foundation.
21  * All rights reserved.
22  *
23  * 
24  * Contributor(s): Blender Foundation
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/windowmanager/intern/wm_init_exit.c
30  *  \ingroup wm
31  */
32
33
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37
38 #include "MEM_guardedalloc.h"
39 #include "MEM_CacheLimiterC-Api.h"
40
41 #include "IMB_imbuf_types.h"
42 #include "IMB_imbuf.h"
43
44 #include "DNA_object_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_userdef_types.h"
47 #include "DNA_windowmanager_types.h"
48
49 #include "BKE_blender.h"
50 #include "BKE_context.h"
51 #include "BKE_screen.h"
52 #include "BKE_curve.h"
53 #include "BKE_displist.h"
54 #include "BKE_DerivedMesh.h"
55 #include "BKE_font.h"
56 #include "BKE_global.h"
57 #include "BKE_library.h"
58 #include "BKE_main.h"
59 #include "BKE_mball.h"
60 #include "BKE_report.h"
61
62 #include "BKE_packedFile.h"
63 #include "BKE_sequencer.h" /* free seq clipboard */
64 #include "BKE_material.h" /* clear_matcopybuf */
65
66 #include "BLI_blenlib.h"
67 #include "BLI_winstuff.h"
68
69 #include "RE_pipeline.h"                /* RE_ free stuff */
70
71 #ifdef WITH_PYTHON
72 #include "BPY_extern.h"
73 #endif
74
75 #ifdef WITH_GAMEENGINE
76 #include "BL_System.h"
77 #endif
78 #include "GHOST_Path-api.h"
79 #include "GHOST_C-api.h"
80
81 #include "RNA_define.h"
82
83 #include "WM_api.h"
84 #include "WM_types.h"
85
86 #include "wm_cursors.h"
87 #include "wm_event_system.h"
88 #include "wm.h"
89 #include "wm_files.h"
90 #include "wm_window.h"
91
92 #include "ED_armature.h"
93 #include "ED_keyframing.h"
94 #include "ED_node.h"
95 #include "ED_render.h"
96 #include "ED_space_api.h"
97 #include "ED_screen.h"
98 #include "ED_util.h"
99
100 #include "UI_interface.h"
101 #include "BLF_api.h"
102
103 #include "GPU_buffers.h"
104 #include "GPU_extensions.h"
105 #include "GPU_draw.h"
106
107 #include "BKE_depsgraph.h"
108 #include "BKE_sound.h"
109
110 static void wm_init_reports(bContext *C)
111 {
112         BKE_reports_init(CTX_wm_reports(C), RPT_STORE);
113 }
114 static void wm_free_reports(bContext *C)
115 {
116         BKE_reports_clear(CTX_wm_reports(C));
117 }
118
119 int wm_start_with_console = 0; /* used in creator.c */
120
121 /* only called once, for startup */
122 void WM_init(bContext *C, int argc, const char **argv)
123 {
124         if (!G.background) {
125                 wm_ghost_init(C);       /* note: it assigns C to ghost! */
126                 wm_init_cursor_data();
127         }
128         GHOST_CreateSystemPaths();
129         wm_operatortype_init();
130         WM_menutype_init();
131
132         set_free_windowmanager_cb(wm_close_and_free);   /* library.c */
133         set_blender_test_break_cb(wm_window_testbreak); /* blender.c */
134         DAG_editors_update_cb(ED_render_id_flush_update); /* depsgraph.c */
135         
136         ED_spacetypes_init();   /* editors/space_api/spacetype.c */
137         
138         ED_file_init();                 /* for fsmenu */
139         ED_init_node_butfuncs();        
140         
141         BLF_init(11, U.dpi); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */
142         BLF_lang_init();
143         /* get the default database, plus a wm */
144         WM_read_homefile(C, NULL, G.factory_startup);
145
146         /* note: there is a bug where python needs initializing before loading the
147          * startup.blend because it may contain PyDrivers. It also needs to be after
148          * initializing space types and other internal data.
149          *
150          * However cant redo this at the moment. Solution is to load python
151          * before WM_read_homefile() or make py-drivers check if python is running.
152          * Will try fix when the crash can be repeated. - campbell. */
153
154 #ifdef WITH_PYTHON
155         BPY_context_set(C); /* necessary evil */
156         BPY_python_start(argc, argv);
157
158         BPY_driver_reset();
159         BPY_app_handlers_reset(); /* causes addon callbacks to be freed [#28068],
160                                    * but this is actually what we want. */
161         BPY_modules_load_user(C);
162 #else
163         (void)argc; /* unused */
164         (void)argv; /* unused */
165 #endif
166
167         if (!G.background && !wm_start_with_console)
168                 GHOST_toggleConsole(3);
169
170         wm_init_reports(C); /* reports cant be initialized before the wm */
171
172         if (!G.background) {
173                 GPU_extensions_init();
174                 GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP));
175                 GPU_set_anisotropic(U.anisotropic_filter);
176         
177                 UI_init();
178         }
179         
180         clear_matcopybuf();
181         ED_render_clear_mtex_copybuf();
182
183         //      glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
184                 
185         ED_preview_init_dbase();
186         
187         WM_read_history();
188
189         /* allow a path of "", this is what happens when making a new file */
190         /*
191         if(G.main->name[0] == 0)
192                 BLI_make_file_string("/", G.main->name, BLI_getDefaultDocumentFolder(), "untitled.blend");
193         */
194
195         BLI_strncpy(G.lib, G.main->name, FILE_MAX);
196 }
197
198 void WM_init_splash(bContext *C)
199 {
200         if((U.uiflag & USER_SPLASH_DISABLE) == 0) {
201                 wmWindowManager *wm= CTX_wm_manager(C);
202                 wmWindow *prevwin= CTX_wm_window(C);
203         
204                 if(wm->windows.first) {
205                         CTX_wm_window_set(C, wm->windows.first);
206                         WM_operator_name_call(C, "WM_OT_splash", WM_OP_INVOKE_DEFAULT, NULL);
207                         CTX_wm_window_set(C, prevwin);
208                 }
209         }
210 }
211
212 static ScrArea *biggest_view3d(bContext *C)
213 {
214         bScreen *sc= CTX_wm_screen(C);
215         ScrArea *sa, *big= NULL;
216         int size, maxsize= 0;
217
218         for(sa= sc->areabase.first; sa; sa= sa->next) {
219                 if(sa->spacetype==SPACE_VIEW3D) {
220                         size= sa->winx * sa->winy;
221                         if(size > maxsize) {
222                                 maxsize= size;
223                                 big= sa;
224                         }
225                 }
226         }
227         return big;
228 }
229
230 int WM_init_game(bContext *C)
231 {
232         wmWindowManager *wm= CTX_wm_manager(C);
233         wmWindow* win;
234
235         ScrArea *sa;
236         ARegion *ar= NULL;
237
238         Scene *scene= CTX_data_scene(C);
239
240         if (!scene) {
241                 // XXX, this should not be needed.
242                 Main *bmain = CTX_data_main(C);
243                 scene= bmain->scene.first;
244         }
245
246         win = wm->windows.first;
247
248         //first to get a valid window
249         if(win)
250                 CTX_wm_window_set(C, win);
251
252         sa = biggest_view3d(C);
253         ar= BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
254
255         // if we have a valid 3D view
256         if (sa && ar) {
257                 ARegion *arhide;
258
259                 CTX_wm_area_set(C, sa);
260                 CTX_wm_region_set(C, ar);
261
262                 /* disable quad view */
263                 if(ar->alignment == RGN_ALIGN_QSPLIT)
264                         WM_operator_name_call(C, "SCREEN_OT_region_quadview", WM_OP_EXEC_DEFAULT, NULL);
265
266                 /* toolbox, properties panel and header are hidden */
267                 for(arhide=sa->regionbase.first; arhide; arhide=arhide->next) {
268                         if(arhide->regiontype != RGN_TYPE_WINDOW) {
269                                 if(!(arhide->flag & RGN_FLAG_HIDDEN)) {
270                                         ED_region_toggle_hidden(C, arhide);
271                                 }
272                         }
273                 }
274
275                 /* full screen the area */
276                 if(!sa->full) {
277                         ED_screen_full_toggle(C, win, sa);
278                 }
279
280                 /* Fullscreen */
281                 if(scene->gm.fullscreen) {
282                         WM_operator_name_call(C, "WM_OT_window_fullscreen_toggle", WM_OP_EXEC_DEFAULT, NULL);
283                         wm_get_screensize(&ar->winrct.xmax, &ar->winrct.ymax);
284                         ar->winx = ar->winrct.xmax + 1;
285                         ar->winy = ar->winrct.ymax + 1;
286                 }
287                 else
288                 {
289                         GHOST_RectangleHandle rect = GHOST_GetClientBounds(win->ghostwin);
290                         ar->winrct.ymax = GHOST_GetHeightRectangle(rect);
291                         ar->winrct.xmax = GHOST_GetWidthRectangle(rect);
292                         ar->winx = ar->winrct.xmax + 1;
293                         ar->winy = ar->winrct.ymax + 1;
294                         GHOST_DisposeRectangle(rect);
295                 }
296
297                 WM_operator_name_call(C, "VIEW3D_OT_game_start", WM_OP_EXEC_DEFAULT, NULL);
298
299                 sound_exit();
300
301                 return 1;
302         }
303         else
304         {
305                 ReportTimerInfo *rti;
306
307                 BKE_report(&wm->reports, RPT_ERROR, "No valid 3D View found. Game auto start is not possible.");
308
309                 /* After adding the report to the global list, reset the report timer. */
310                 WM_event_remove_timer(wm, NULL, wm->reports.reporttimer);
311
312                 /* Records time since last report was added */
313                 wm->reports.reporttimer = WM_event_add_timer(wm, CTX_wm_window(C), TIMER, 0.02);
314
315                 rti = MEM_callocN(sizeof(ReportTimerInfo), "ReportTimerInfo");
316                 wm->reports.reporttimer->customdata = rti;
317         }
318         return 0;
319 }
320
321 /* free strings of open recent files */
322 static void free_openrecent(void)
323 {
324         struct RecentFile *recent;
325         
326         for(recent = G.recent_files.first; recent; recent=recent->next)
327                 MEM_freeN(recent->filepath);
328         
329         BLI_freelistN(&(G.recent_files));
330 }
331
332
333 /* bad stuff*/
334
335 extern wchar_t *copybuf;
336 extern wchar_t *copybufinfo;
337
338         // XXX copy/paste buffer stuff...
339 extern void free_anim_copybuf(void); 
340 extern void free_anim_drivers_copybuf(void); 
341 extern void free_fmodifiers_copybuf(void); 
342 extern void free_posebuf(void); 
343
344 /* called in creator.c even... tsk, split this! */
345 /* note, doesnt run exit() call WM_exit() for that */
346 void WM_exit_ext(bContext *C, const short do_python)
347 {
348         wmWindow *win;
349
350         sound_exit();
351
352
353         /* first wrap up running stuff, we assume only the active WM is running */
354         /* modal handlers are on window level freed, others too? */
355         /* note; same code copied in wm_files.c */
356         if(C && CTX_wm_manager(C)) {
357                 
358                 WM_jobs_stop_all(CTX_wm_manager(C));
359                 
360                 for(win= CTX_wm_manager(C)->windows.first; win; win= win->next) {
361                         
362                         CTX_wm_window_set(C, win);      /* needed by operator close callbacks */
363                         WM_event_remove_handlers(C, &win->handlers);
364                         WM_event_remove_handlers(C, &win->modalhandlers);
365                         ED_screen_exit(C, win, win->screen);
366                 }
367         }
368         wm_operatortype_free();
369         wm_dropbox_free();
370         WM_menutype_free();
371         
372         /* all non-screen and non-space stuff editors did, like editmode */
373         if(C)
374                 ED_editors_exit(C);
375
376 //      XXX     
377 //      BIF_GlobalReebFree();
378 //      BIF_freeRetarget();
379         BIF_freeTemplates(C);
380         
381         free_ttfont(); /* bke_font.h */
382         
383         free_openrecent();
384         
385         BKE_freecubetable();
386         
387         ED_preview_free_dbase();        /* frees a Main dbase, before free_blender! */
388
389         if(C && CTX_wm_manager(C))
390                 wm_free_reports(C);                     /* before free_blender! - since the ListBases get freed there */
391
392         seq_free_clipboard(); /* sequencer.c */
393                 
394         free_blender();                         /* blender.c, does entire library and spacetypes */
395 //      free_matcopybuf();
396         free_anim_copybuf();
397         free_anim_drivers_copybuf();
398         free_fmodifiers_copybuf();
399         free_posebuf();
400
401         BLF_exit();
402         
403         ANIM_keyingset_infos_exit();
404         
405         RE_FreeAllRender();
406         RE_engines_exit();
407         
408 //      free_txt_data();
409         
410
411 #ifdef WITH_PYTHON
412         /* option not to close python so we can use 'atexit' */
413         if(do_python) {
414                 /* XXX - old note */
415                 /* before free_blender so py's gc happens while library still exists */
416                 /* needed at least for a rare sigsegv that can happen in pydrivers */
417
418                 /* Update for blender 2.5, move after free_blender because blender now holds references to PyObject's
419                  * so decref'ing them after python ends causes bad problems every time
420                  * the pyDriver bug can be fixed if it happens again we can deal with it then */
421                 BPY_python_end();
422         }
423 #endif
424
425         GPU_global_buffer_pool_free();
426         GPU_free_unused_buffers();
427         GPU_extensions_exit();
428         
429 //      if (copybuf) MEM_freeN(copybuf);
430 //      if (copybufinfo) MEM_freeN(copybufinfo);
431         if (!G.background) {
432                 BKE_undo_save_quit();   // saves quit.blend if global undo is on
433         }
434         BKE_reset_undo(); 
435         
436         ED_file_exit(); /* for fsmenu */
437
438         UI_exit();
439         BKE_userdef_free();
440
441         RNA_exit(); /* should be after BPY_python_end so struct python slots are cleared */
442         
443         wm_ghost_exit();
444
445         CTX_free(C);
446 #ifdef WITH_GAMEENGINE
447         SYS_DeleteSystem(SYS_GetSystem());
448 #endif
449         
450         GHOST_DisposeSystemPaths();
451
452         if(MEM_get_memory_blocks_in_use()!=0) {
453                 printf("Error: Not freed memory blocks: %d\n", MEM_get_memory_blocks_in_use());
454                 MEM_printmemlist();
455         }
456         wm_autosave_delete();
457         
458         printf("\nBlender quit\n");
459         
460 #ifdef WIN32   
461         /* ask user to press enter when in debug mode */
462         if(G.f & G_DEBUG) {
463                 printf("press enter key to exit...\n\n");
464                 getchar();
465         }
466 #endif 
467 }
468
469 void WM_exit(bContext *C)
470 {
471         WM_exit_ext(C, 1);
472         exit(G.afbreek==1);
473 }