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