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