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