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