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