Fix T38541: sys.exit fails when blender is built as a py-module
[blender-staging.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 #include "MEM_CacheLimiterC-Api.h"
43
44 #include "IMB_imbuf_types.h"
45 #include "IMB_imbuf.h"
46
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_userdef_types.h"
50 #include "DNA_windowmanager_types.h"
51
52 #include "BLI_callbacks.h"
53 #include "BLI_listbase.h"
54 #include "BLI_path_util.h"
55 #include "BLI_string.h"
56 #include "BLI_threads.h"
57 #include "BLI_utildefines.h"
58
59 #include "BKE_blender.h"
60 #include "BKE_context.h"
61 #include "BKE_screen.h"
62 #include "BKE_curve.h"
63 #include "BKE_displist.h"
64 #include "BKE_DerivedMesh.h"
65 #include "BKE_font.h"
66 #include "BKE_global.h"
67 #include "BKE_library.h"
68 #include "BKE_main.h"
69 #include "BKE_mball.h"
70 #include "BKE_node.h"
71 #include "BKE_report.h"
72
73 #include "BKE_addon.h"
74 #include "BKE_packedFile.h"
75 #include "BKE_sequencer.h" /* free seq clipboard */
76 #include "BKE_material.h" /* clear_matcopybuf */
77 #include "BKE_tracking.h" /* free tracking clipboard */
78 #include "BKE_mask.h" /* free mask clipboard */
79
80 #include "RE_engine.h"
81 #include "RE_pipeline.h"        /* RE_ free stuff */
82
83 #ifdef WITH_PYTHON
84 #include "BPY_extern.h"
85 #endif
86
87 #ifdef WITH_GAMEENGINE
88 #  include "BL_System.h"
89 #endif
90 #include "GHOST_Path-api.h"
91 #include "GHOST_C-api.h"
92
93 #include "RNA_define.h"
94
95 #include "WM_api.h"
96 #include "WM_types.h"
97
98 #include "wm_cursors.h"
99 #include "wm_event_system.h"
100 #include "wm.h"
101 #include "wm_files.h"
102 #include "wm_window.h"
103
104 #include "ED_armature.h"
105 #include "ED_keyframing.h"
106 #include "ED_node.h"
107 #include "ED_render.h"
108 #include "ED_space_api.h"
109 #include "ED_screen.h"
110 #include "ED_util.h"
111
112 #include "UI_interface.h"
113 #include "BLF_api.h"
114 #include "BLF_translation.h"
115
116 #include "GPU_buffers.h"
117 #include "GPU_extensions.h"
118 #include "GPU_draw.h"
119
120 #include "BKE_depsgraph.h"
121 #include "BKE_sound.h"
122 #include "COM_compositor.h"
123
124 static void wm_init_reports(bContext *C)
125 {
126         BKE_reports_init(CTX_wm_reports(C), RPT_STORE);
127 }
128 static void wm_free_reports(bContext *C)
129 {
130         BKE_reports_clear(CTX_wm_reports(C));
131 }
132
133 bool wm_start_with_console = false; /* used in creator.c */
134
135 /* only called once, for startup */
136 void WM_init(bContext *C, int argc, const char **argv)
137 {
138         
139         if (!G.background) {
140                 wm_ghost_init(C);   /* note: it assigns C to ghost! */
141                 wm_init_cursor_data();
142         }
143         GHOST_CreateSystemPaths();
144
145         BKE_addon_pref_type_init();
146
147         wm_operatortype_init();
148         WM_menutype_init();
149         WM_uilisttype_init();
150
151         set_free_windowmanager_cb(wm_close_and_free);   /* library.c */
152         set_free_notifier_reference_cb(WM_main_remove_notifier_reference);   /* library.c */
153         set_blender_test_break_cb(wm_window_testbreak); /* blender.c */
154         DAG_editors_update_cb(ED_render_id_flush_update, ED_render_scene_update); /* depsgraph.c */
155         
156         ED_spacetypes_init();   /* editors/space_api/spacetype.c */
157         
158         ED_file_init();         /* for fsmenu */
159         ED_node_init_butfuncs();
160         
161         BLF_init(11, U.dpi); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */
162         BLF_lang_init();
163
164         /* get the default database, plus a wm */
165         wm_homefile_read(C, NULL, G.factory_startup, NULL);
166         
167         BLF_lang_set(NULL);
168
169         /* note: there is a bug where python needs initializing before loading the
170          * startup.blend because it may contain PyDrivers. It also needs to be after
171          * initializing space types and other internal data.
172          *
173          * However cant redo this at the moment. Solution is to load python
174          * before wm_homefile_read() or make py-drivers check if python is running.
175          * Will try fix when the crash can be repeated. - campbell. */
176
177 #ifdef WITH_PYTHON
178         BPY_context_set(C); /* necessary evil */
179         BPY_python_start(argc, argv);
180
181         BPY_python_reset(C);
182 #else
183         (void)argc; /* unused */
184         (void)argv; /* unused */
185 #endif
186
187         if (!G.background && !wm_start_with_console)
188                 GHOST_toggleConsole(3);
189
190         wm_init_reports(C); /* reports cant be initialized before the wm */
191
192         if (!G.background) {
193                 GPU_extensions_init();
194                 GPU_set_mipmap(!(U.gameflags & USER_DISABLE_MIPMAP));
195                 GPU_set_anisotropic(U.anisotropic_filter);
196                 GPU_set_gpu_mipmapping(U.use_gpu_mipmap);
197
198                 UI_init();
199         }
200         
201         clear_matcopybuf();
202         ED_render_clear_mtex_copybuf();
203
204         // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
205                 
206         ED_preview_init_dbase();
207         
208         wm_read_history();
209
210         /* allow a path of "", this is what happens when making a new file */
211 #if 0
212         if (G.main->name[0] == 0)
213                 BLI_make_file_string("/", G.main->name, BLI_getDefaultDocumentFolder(), "untitled.blend");
214 #endif
215
216         BLI_strncpy(G.lib, G.main->name, FILE_MAX);
217
218 #ifdef WITH_COMPOSITOR
219         if (1) {
220                 extern void *COM_linker_hack;
221                 COM_linker_hack = COM_execute;
222         }
223 #endif
224         
225         /* load last session, uses regular file reading so it has to be in end (after init py etc) */
226         if (U.uiflag2 & USER_KEEP_SESSION) {
227                 /* calling WM_recover_last_session(C, NULL) has been moved to creator.c */
228                 /* that prevents loading both the kept session, and the file on the command line */
229         }
230         else {
231                 /* normally 'wm_homefile_read' will do this,
232                  * however python is not initialized when called from this function.
233                  *
234                  * unlikely any handlers are set but its possible,
235                  * note that recovering the last session does its own callbacks. */
236                 BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_POST);
237         }
238 }
239
240 void WM_init_splash(bContext *C)
241 {
242         if ((U.uiflag & USER_SPLASH_DISABLE) == 0) {
243                 wmWindowManager *wm = CTX_wm_manager(C);
244                 wmWindow *prevwin = CTX_wm_window(C);
245         
246                 if (wm->windows.first) {
247                         CTX_wm_window_set(C, wm->windows.first);
248                         WM_operator_name_call(C, "WM_OT_splash", WM_OP_INVOKE_DEFAULT, NULL);
249                         CTX_wm_window_set(C, prevwin);
250                 }
251         }
252 }
253
254 bool WM_init_game(bContext *C)
255 {
256         wmWindowManager *wm = CTX_wm_manager(C);
257         wmWindow *win;
258
259         ScrArea *sa;
260         ARegion *ar = NULL;
261
262         Scene *scene = CTX_data_scene(C);
263
264         if (!scene) {
265                 /* XXX, this should not be needed. */
266                 Main *bmain = CTX_data_main(C);
267                 scene = bmain->scene.first;
268         }
269
270         win = wm->windows.first;
271
272         /* first to get a valid window */
273         if (win)
274                 CTX_wm_window_set(C, win);
275
276         sa = BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_VIEW3D, 0);
277         ar = BKE_area_find_region_type(sa, RGN_TYPE_WINDOW);
278
279         /* if we have a valid 3D view */
280         if (sa && ar) {
281                 ARegion *arhide;
282
283                 CTX_wm_area_set(C, sa);
284                 CTX_wm_region_set(C, ar);
285
286                 /* disable quad view */
287                 if (ar->alignment == RGN_ALIGN_QSPLIT)
288                         WM_operator_name_call(C, "SCREEN_OT_region_quadview", WM_OP_EXEC_DEFAULT, NULL);
289
290                 /* toolbox, properties panel and header are hidden */
291                 for (arhide = sa->regionbase.first; arhide; arhide = arhide->next) {
292                         if (arhide->regiontype != RGN_TYPE_WINDOW) {
293                                 if (!(arhide->flag & RGN_FLAG_HIDDEN)) {
294                                         ED_region_toggle_hidden(C, arhide);
295                                 }
296                         }
297                 }
298
299                 /* full screen the area */
300                 if (!sa->full) {
301                         ED_screen_full_toggle(C, win, sa);
302                 }
303
304                 /* Fullscreen */
305                 if ((scene->gm.playerflag & GAME_PLAYER_FULLSCREEN)) {
306                         WM_operator_name_call(C, "WM_OT_window_fullscreen_toggle", WM_OP_EXEC_DEFAULT, NULL);
307                         wm_get_screensize(&ar->winrct.xmax, &ar->winrct.ymax);
308                         ar->winx = ar->winrct.xmax + 1;
309                         ar->winy = ar->winrct.ymax + 1;
310                 }
311                 else {
312                         GHOST_RectangleHandle rect = GHOST_GetClientBounds(win->ghostwin);
313                         ar->winrct.ymax = GHOST_GetHeightRectangle(rect);
314                         ar->winrct.xmax = GHOST_GetWidthRectangle(rect);
315                         ar->winx = ar->winrct.xmax + 1;
316                         ar->winy = ar->winrct.ymax + 1;
317                         GHOST_DisposeRectangle(rect);
318                 }
319
320                 WM_operator_name_call(C, "VIEW3D_OT_game_start", WM_OP_EXEC_DEFAULT, NULL);
321
322                 sound_exit();
323
324                 return true;
325         }
326         else {
327                 ReportTimerInfo *rti;
328
329                 BKE_report(&wm->reports, RPT_ERROR, "No valid 3D View found, game auto start is not possible");
330
331                 /* After adding the report to the global list, reset the report timer. */
332                 WM_event_remove_timer(wm, NULL, wm->reports.reporttimer);
333
334                 /* Records time since last report was added */
335                 wm->reports.reporttimer = WM_event_add_timer(wm, CTX_wm_window(C), TIMER, 0.02);
336
337                 rti = MEM_callocN(sizeof(ReportTimerInfo), "ReportTimerInfo");
338                 wm->reports.reporttimer->customdata = rti;
339
340                 return false;
341         }
342 }
343
344 /* free strings of open recent files */
345 static void free_openrecent(void)
346 {
347         struct RecentFile *recent;
348         
349         for (recent = G.recent_files.first; recent; recent = recent->next)
350                 MEM_freeN(recent->filepath);
351         
352         BLI_freelistN(&(G.recent_files));
353 }
354
355
356 /* bad stuff*/
357
358 // XXX copy/paste buffer stuff...
359 extern void free_anim_copybuf(void);
360 extern void free_anim_drivers_copybuf(void);
361 extern void free_fmodifiers_copybuf(void);
362
363 #ifdef WIN32
364 /* Read console events until there is a key event.  Also returns on any error. */
365 static void wait_for_console_key(void)
366 {
367         HANDLE hConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
368
369         if (!ELEM(hConsoleInput, NULL, INVALID_HANDLE_VALUE) && FlushConsoleInputBuffer(hConsoleInput)) {
370                 for (;;) {
371                         INPUT_RECORD buffer;
372                         DWORD ignored;
373
374                         if (!ReadConsoleInput(hConsoleInput, &buffer, 1, &ignored)) {
375                                 break;
376                         }
377
378                         if (buffer.EventType == KEY_EVENT) {
379                                 break;
380                         }
381                 }
382         }
383 }
384 #endif
385
386 /* called in creator.c even... tsk, split this! */
387 /* note, doesnt run exit() call WM_exit() for that */
388 void WM_exit_ext(bContext *C, const bool do_python)
389 {
390         wmWindowManager *wm = C ? CTX_wm_manager(C) : NULL;
391
392         sound_exit();
393
394         /* first wrap up running stuff, we assume only the active WM is running */
395         /* modal handlers are on window level freed, others too? */
396         /* note; same code copied in wm_files.c */
397         if (C && wm) {
398                 wmWindow *win;
399
400                 if (!G.background) {
401                         if ((U.uiflag2 & USER_KEEP_SESSION) || BKE_undo_valid(NULL)) {
402                                 /* save the undo state as quit.blend */
403                                 char filename[FILE_MAX];
404                                 
405                                 BLI_make_file_string("/", filename, BLI_temporary_dir(), BLENDER_QUIT_FILE);
406
407                                 if (BKE_undo_save_file(filename))
408                                         printf("Saved session recovery to '%s'\n", filename);
409                         }
410                 }
411                 
412                 WM_jobs_kill_all(wm);
413
414                 for (win = wm->windows.first; win; win = win->next) {
415                         
416                         CTX_wm_window_set(C, win);  /* needed by operator close callbacks */
417                         WM_event_remove_handlers(C, &win->handlers);
418                         WM_event_remove_handlers(C, &win->modalhandlers);
419                         ED_screen_exit(C, win, win->screen);
420                 }
421         }
422
423         BKE_addon_pref_type_free();
424         wm_operatortype_free();
425         wm_dropbox_free();
426         WM_menutype_free();
427         WM_uilisttype_free();
428         
429         /* all non-screen and non-space stuff editors did, like editmode */
430         if (C)
431                 ED_editors_exit(C);
432
433 //      XXX     
434 //      BIF_GlobalReebFree();
435 //      BIF_freeRetarget();
436         BIF_freeTemplates(C);
437
438         free_openrecent();
439         
440         BKE_mball_cubeTable_free();
441         
442         /* render code might still access databases */
443         RE_FreeAllRender();
444         RE_engines_exit();
445         
446         ED_preview_free_dbase();  /* frees a Main dbase, before free_blender! */
447
448         if (C && wm)
449                 wm_free_reports(C);  /* before free_blender! - since the ListBases get freed there */
450
451         BKE_sequencer_free_clipboard(); /* sequencer.c */
452         BKE_tracking_clipboard_free();
453         BKE_mask_clipboard_free();
454                 
455 #ifdef WITH_COMPOSITOR
456         COM_deinitialize();
457 #endif
458         
459         free_blender();  /* blender.c, does entire library and spacetypes */
460 //      free_matcopybuf();
461         free_anim_copybuf();
462         free_anim_drivers_copybuf();
463         free_fmodifiers_copybuf();
464         ED_clipboard_posebuf_free();
465         BKE_node_clipboard_clear();
466
467         BLF_exit();
468
469 #ifdef WITH_INTERNATIONAL
470         BLF_free_unifont();
471         BLF_free_unifont_mono();
472         BLF_lang_free();
473 #endif
474         
475         ANIM_keyingset_infos_exit();
476         
477 //      free_txt_data();
478         
479
480 #ifdef WITH_PYTHON
481         /* option not to close python so we can use 'atexit' */
482         if (do_python) {
483                 /* XXX - old note */
484                 /* before free_blender so py's gc happens while library still exists */
485                 /* needed at least for a rare sigsegv that can happen in pydrivers */
486
487                 /* Update for blender 2.5, move after free_blender because blender now holds references to PyObject's
488                  * so decref'ing them after python ends causes bad problems every time
489                  * the pyDriver bug can be fixed if it happens again we can deal with it then */
490                 BPY_python_end();
491         }
492 #else
493         (void)do_python;
494 #endif
495
496         GPU_global_buffer_pool_free();
497         GPU_free_unused_buffers();
498         GPU_extensions_exit();
499
500         BKE_reset_undo(); 
501         
502         ED_file_exit(); /* for fsmenu */
503
504         UI_exit();
505         BKE_userdef_free();
506
507         RNA_exit(); /* should be after BPY_python_end so struct python slots are cleared */
508         
509         wm_ghost_exit();
510
511         CTX_free(C);
512 #ifdef WITH_GAMEENGINE
513         SYS_DeleteSystem(SYS_GetSystem());
514 #endif
515         
516         GHOST_DisposeSystemPaths();
517
518         BLI_threadapi_exit();
519
520         if (MEM_get_memory_blocks_in_use() != 0) {
521                 printf("Error: Not freed memory blocks: %d\n", MEM_get_memory_blocks_in_use());
522                 MEM_printmemlist();
523         }
524         wm_autosave_delete();
525 }
526
527 void WM_exit(bContext *C)
528 {
529         WM_exit_ext(C, 1);
530
531         printf("\nBlender quit\n");
532
533 #ifdef WIN32
534         /* ask user to press a key when in debug mode */
535         if (G.debug & G_DEBUG) {
536                 printf("Press any key to exit . . .\n\n");
537                 wait_for_console_key();
538         }
539 #endif
540
541         exit(G.is_break == TRUE);
542 }