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