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