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