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