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