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