Fix assert when loading file with multiple windows opened
[blender.git] / source / blender / windowmanager / intern / wm_window.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 but based
19  * on ghostwinlay.c (C) 2001-2002 by NaN Holding BV
20  * All rights reserved.
21  *
22  * Contributor(s): Blender Foundation, 2008
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/windowmanager/intern/wm_window.c
28  *  \ingroup wm
29  *
30  * Window management, wrap GHOST.
31  */
32
33 #include <math.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37
38 #include "DNA_listBase.h"
39 #include "DNA_screen_types.h"
40 #include "DNA_windowmanager_types.h"
41 #include "DNA_workspace_types.h"
42
43 #include "MEM_guardedalloc.h"
44
45 #include "GHOST_C-api.h"
46
47 #include "BLI_math.h"
48 #include "BLI_blenlib.h"
49 #include "BLI_utildefines.h"
50
51 #include "BLT_translation.h"
52
53 #include "BKE_blender.h"
54 #include "BKE_context.h"
55 #include "BKE_icons.h"
56 #include "BKE_layer.h"
57 #include "BKE_library.h"
58 #include "BKE_global.h"
59 #include "BKE_main.h"
60 #include "BKE_screen.h"
61 #include "BKE_workspace.h"
62
63 #include "RNA_access.h"
64 #include "RNA_define.h"
65 #include "RNA_enum_types.h"
66
67 #include "WM_api.h"
68 #include "WM_types.h"
69 #include "wm.h"
70 #include "wm_draw.h"
71 #include "wm_window.h"
72 #include "wm_event_system.h"
73
74 #include "ED_anim_api.h"
75 #include "ED_scene.h"
76 #include "ED_screen.h"
77 #include "ED_fileselect.h"
78
79 #include "UI_interface.h"
80 #include "UI_interface_icons.h"
81
82 #include "PIL_time.h"
83
84 #include "GPU_batch.h"
85 #include "GPU_batch_presets.h"
86 #include "GPU_draw.h"
87 #include "GPU_extensions.h"
88 #include "GPU_framebuffer.h"
89 #include "GPU_init_exit.h"
90 #include "GPU_immediate.h"
91 #include "GPU_material.h"
92 #include "GPU_texture.h"
93 #include "GPU_context.h"
94 #include "BLF_api.h"
95
96 #include "UI_resources.h"
97
98 /* for assert */
99 #ifndef NDEBUG
100 #  include "BLI_threads.h"
101 #endif
102
103 /* the global to talk to ghost */
104 static GHOST_SystemHandle g_system = NULL;
105
106 typedef enum WinOverrideFlag {
107         WIN_OVERRIDE_GEOM     = (1 << 0),
108         WIN_OVERRIDE_WINSTATE = (1 << 1)
109 } WinOverrideFlag;
110
111 /* set by commandline */
112 static struct WMInitStruct {
113         /* window geometry */
114         int size_x, size_y;
115         int start_x, start_y;
116
117         int windowstate;
118         WinOverrideFlag override_flag;
119
120         bool native_pixels;
121 } wm_init_state = {0, 0, 0, 0, GHOST_kWindowStateNormal, 0, true};
122
123 /* ******** win open & close ************ */
124
125 static void wm_window_set_drawable(wmWindowManager *wm, wmWindow *win, bool activate);
126
127 /* XXX this one should correctly check for apple top header...
128  * done for Cocoa : returns window contents (and not frame) max size*/
129 void wm_get_screensize(int *r_width, int *r_height)
130 {
131         unsigned int uiwidth;
132         unsigned int uiheight;
133
134         GHOST_GetMainDisplayDimensions(g_system, &uiwidth, &uiheight);
135         *r_width = uiwidth;
136         *r_height = uiheight;
137 }
138
139 /* size of all screens (desktop), useful since the mouse is bound by this */
140 void wm_get_desktopsize(int *r_width, int *r_height)
141 {
142         unsigned int uiwidth;
143         unsigned int uiheight;
144
145         GHOST_GetAllDisplayDimensions(g_system, &uiwidth, &uiheight);
146         *r_width = uiwidth;
147         *r_height = uiheight;
148 }
149
150 /* keeps offset and size within monitor bounds */
151 /* XXX solve dual screen... */
152 static void wm_window_check_position(rcti *rect)
153 {
154         int width, height, d;
155
156         wm_get_screensize(&width, &height);
157
158         if (rect->xmin < 0) {
159                 rect->xmax -= rect->xmin;
160                 rect->xmin  = 0;
161         }
162         if (rect->ymin < 0) {
163                 rect->ymax -= rect->ymin;
164                 rect->ymin  = 0;
165         }
166         if (rect->xmax > width) {
167                 d = rect->xmax - width;
168                 rect->xmax -= d;
169                 rect->xmin -= d;
170         }
171         if (rect->ymax > height) {
172                 d = rect->ymax - height;
173                 rect->ymax -= d;
174                 rect->ymin -= d;
175         }
176
177         if (rect->xmin < 0) rect->xmin = 0;
178         if (rect->ymin < 0) rect->ymin = 0;
179 }
180
181 static void wm_ghostwindow_destroy(wmWindowManager *wm, wmWindow *win)
182 {
183         if (win->ghostwin) {
184                 /* Prevents non-drawable state of main windows (bugs #22967,
185                  * #25071 and possibly #22477 too). Always clear it even if
186                  * this window was not the drawable one, because we mess with
187                  * drawing context to discard the GW context. */
188                 wm_window_clear_drawable(wm);
189
190                 if (win == wm->winactive) {
191                         wm->winactive = NULL;
192                 }
193
194                 /* We need this window's opengl context active to discard it. */
195                 GHOST_ActivateWindowDrawingContext(win->ghostwin);
196                 GPU_context_active_set(win->gpuctx);
197
198                 /* Delete local gpu context.  */
199                 GPU_context_discard(win->gpuctx);
200
201                 GHOST_DisposeWindow(g_system, win->ghostwin);
202                 win->ghostwin = NULL;
203                 win->gpuctx = NULL;
204         }
205 }
206
207 /* including window itself, C can be NULL.
208  * ED_screen_exit should have been called */
209 void wm_window_free(bContext *C, wmWindowManager *wm, wmWindow *win)
210 {
211         wmTimer *wt, *wtnext;
212
213         /* update context */
214         if (C) {
215                 WM_event_remove_handlers(C, &win->handlers);
216                 WM_event_remove_handlers(C, &win->modalhandlers);
217
218                 if (CTX_wm_window(C) == win)
219                         CTX_wm_window_set(C, NULL);
220         }
221
222         BKE_screen_area_map_free(&win->global_areas);
223
224         /* end running jobs, a job end also removes its timer */
225         for (wt = wm->timers.first; wt; wt = wtnext) {
226                 wtnext = wt->next;
227                 if (wt->win == win && wt->event_type == TIMERJOBS)
228                         wm_jobs_timer_ended(wm, wt);
229         }
230
231         /* timer removing, need to call this api function */
232         for (wt = wm->timers.first; wt; wt = wtnext) {
233                 wtnext = wt->next;
234                 if (wt->win == win)
235                         WM_event_remove_timer(wm, win, wt);
236         }
237
238         if (win->eventstate) MEM_freeN(win->eventstate);
239
240         if (win->cursor_keymap_status) {
241                 MEM_freeN(win->cursor_keymap_status);
242         }
243
244         wm_event_free_all(win);
245
246         wm_ghostwindow_destroy(wm, win);
247
248         BKE_workspace_instance_hook_free(G_MAIN, win->workspace_hook);
249         MEM_freeN(win->stereo3d_format);
250
251         MEM_freeN(win);
252 }
253
254 static int find_free_winid(wmWindowManager *wm)
255 {
256         wmWindow *win;
257         int id = 1;
258
259         for (win = wm->windows.first; win; win = win->next)
260                 if (id <= win->winid)
261                         id = win->winid + 1;
262
263         return id;
264 }
265
266 /* don't change context itself */
267 wmWindow *wm_window_new(bContext *C, wmWindow *parent)
268 {
269         Main *bmain = CTX_data_main(C);
270         wmWindowManager *wm = CTX_wm_manager(C);
271         wmWindow *win = MEM_callocN(sizeof(wmWindow), "window");
272
273         BLI_addtail(&wm->windows, win);
274         win->winid = find_free_winid(wm);
275
276         win->parent = (parent && parent->parent) ? parent->parent : parent;
277         win->stereo3d_format = MEM_callocN(sizeof(Stereo3dFormat), "Stereo 3D Format (window)");
278         win->workspace_hook = BKE_workspace_instance_hook_create(bmain);
279
280         return win;
281 }
282
283 /* part of wm_window.c api */
284 wmWindow *wm_window_copy(bContext *C, wmWindow *win_src, const bool duplicate_layout, const bool child)
285 {
286         Main *bmain = CTX_data_main(C);
287         wmWindow *win_parent = (child) ? win_src : win_src->parent;
288         wmWindow *win_dst = wm_window_new(C, win_parent);
289         WorkSpace *workspace = WM_window_get_active_workspace(win_src);
290         WorkSpaceLayout *layout_old = WM_window_get_active_layout(win_src);
291         WorkSpaceLayout *layout_new;
292
293         win_dst->posx = win_src->posx + 10;
294         win_dst->posy = win_src->posy;
295         win_dst->sizex = win_src->sizex;
296         win_dst->sizey = win_src->sizey;
297
298         win_dst->scene = win_src->scene;
299         STRNCPY(win_dst->view_layer_name, win_src->view_layer_name);
300         BKE_workspace_active_set(win_dst->workspace_hook, workspace);
301         layout_new = duplicate_layout ? ED_workspace_layout_duplicate(bmain, workspace, layout_old, win_dst) : layout_old;
302         BKE_workspace_hook_layout_for_workspace_set(win_dst->workspace_hook, workspace, layout_new);
303
304         *win_dst->stereo3d_format = *win_src->stereo3d_format;
305
306         return win_dst;
307 }
308
309 /**
310  * A higher level version of copy that tests the new window can be added.
311  * (called from the operator directly)
312  */
313 wmWindow *wm_window_copy_test(bContext *C, wmWindow *win_src, const bool duplicate_layout, const bool child)
314 {
315         wmWindowManager *wm = CTX_wm_manager(C);
316         wmWindow *win_dst;
317
318         win_dst = wm_window_copy(C, win_src, duplicate_layout, child);
319
320         WM_check(C);
321
322         if (win_dst->ghostwin) {
323                 WM_event_add_notifier(C, NC_WINDOW | NA_ADDED, NULL);
324                 return win_dst;
325         }
326         else {
327                 wm_window_close(C, wm, win_dst);
328                 return NULL;
329         }
330 }
331
332
333 /* -------------------------------------------------------------------- */
334 /** \name Quit Confirmation Dialog
335  * \{ */
336
337 /** Cancel quitting and close the dialog */
338 static void wm_block_confirm_quit_cancel(bContext *C, void *arg_block, void *UNUSED(arg))
339 {
340         wmWindow *win = CTX_wm_window(C);
341         UI_popup_block_close(C, win, arg_block);
342 }
343
344 /** Discard the file changes and quit */
345 static void wm_block_confirm_quit_discard(bContext *C, void *arg_block, void *UNUSED(arg))
346 {
347         wmWindow *win = CTX_wm_window(C);
348         UI_popup_block_close(C, win, arg_block);
349         WM_exit(C);
350 }
351
352 /* Save changes and quit */
353 static void wm_block_confirm_quit_save(bContext *C, void *arg_block, void *UNUSED(arg))
354 {
355         PointerRNA props_ptr;
356         wmWindow *win = CTX_wm_window(C);
357
358         UI_popup_block_close(C, win, arg_block);
359
360         wmOperatorType *ot = WM_operatortype_find("WM_OT_save_mainfile", false);
361
362         WM_operator_properties_create_ptr(&props_ptr, ot);
363         RNA_boolean_set(&props_ptr, "exit", true);
364         /* No need for second confirmation popup. */
365         RNA_boolean_set(&props_ptr, "check_existing", false);
366         WM_operator_name_call_ptr(C, ot, WM_OP_INVOKE_DEFAULT, &props_ptr);
367         WM_operator_properties_free(&props_ptr);
368 }
369
370
371 /* Build the confirm dialog UI */
372 static uiBlock *block_create_confirm_quit(struct bContext *C, struct ARegion *ar, void *UNUSED(arg1))
373 {
374         Main *bmain = CTX_data_main(C);
375
376         uiStyle *style = UI_style_get();
377         uiBlock *block = UI_block_begin(C, ar, "confirm_quit_popup", UI_EMBOSS);
378
379         UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_LOOP | UI_BLOCK_NO_WIN_CLIP | UI_BLOCK_NUMSELECT);
380         UI_block_emboss_set(block, UI_EMBOSS);
381
382         uiLayout *layout = UI_block_layout(
383                 block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, U.widget_unit * 24, U.widget_unit * 6, 0, style);
384
385         /* Text and some vertical space */
386         {
387                 char *message;
388                 if (BKE_main_blendfile_path(bmain)[0] == '\0') {
389                         message = BLI_strdup(IFACE_("This file has not been saved yet. Save before closing?"));
390                 }
391                 else {
392                         const char *basename = BLI_path_basename(BKE_main_blendfile_path(bmain));
393                         message = BLI_sprintfN(IFACE_("Save changes to \"%s\" before closing?"), basename);
394                 }
395                 uiItemL(layout, message, ICON_ERROR);
396                 MEM_freeN(message);
397         }
398
399         uiItemS(layout);
400         uiItemS(layout);
401
402
403         /* Buttons */
404         uiBut *but;
405
406         uiLayout *split = uiLayoutSplit(layout, 0.0f, true);
407
408         uiLayout *col = uiLayoutColumn(split, false);
409
410         but = uiDefIconTextBut(
411                 block, UI_BTYPE_BUT, 0, ICON_SCREEN_BACK, IFACE_("Cancel"), 0, 0, 0, UI_UNIT_Y,
412                 NULL, 0, 0, 0, 0, TIP_("Do not quit"));
413         UI_but_func_set(but, wm_block_confirm_quit_cancel, block, NULL);
414
415         /* empty space between buttons */
416         col = uiLayoutColumn(split, false);
417         uiItemS(col);
418
419         col = uiLayoutColumn(split, 1);
420         but = uiDefIconTextBut(
421                 block, UI_BTYPE_BUT, 0, ICON_CANCEL, IFACE_("Discard Changes"), 0, 0, 50, UI_UNIT_Y,
422                 NULL, 0, 0, 0, 0, TIP_("Discard changes and quit"));
423         UI_but_func_set(but, wm_block_confirm_quit_discard, block, NULL);
424
425         col = uiLayoutColumn(split, 1);
426         but = uiDefIconTextBut(
427                 block, UI_BTYPE_BUT, 0, ICON_FILE_TICK, IFACE_("Save & Quit"), 0, 0, 50, UI_UNIT_Y,
428                 NULL, 0, 0, 0, 0, TIP_("Save and quit"));
429         UI_but_func_set(but, wm_block_confirm_quit_save, block, NULL);
430
431         UI_block_bounds_set_centered(block, 10);
432
433         return block;
434 }
435
436
437 /**
438  * Call the confirm dialog on quitting. It's displayed in the context window so
439  * caller should set it as desired.
440  */
441 static void wm_confirm_quit(bContext *C)
442 {
443         wmWindow *win = CTX_wm_window(C);
444
445         if (GHOST_SupportsNativeDialogs() == 0) {
446                 UI_popup_block_invoke(C, block_create_confirm_quit, NULL);
447         }
448         else if (GHOST_confirmQuit(win->ghostwin)) {
449                 wm_exit_schedule_delayed(C);
450         }
451 }
452
453 /**
454  * Call the quit confirmation prompt or exit directly if needed. The use can
455  * still cancel via the confirmation popup. Also, this may not quit Blender
456  * immediately, but rather schedule the closing.
457  *
458  * \param win The window to show the confirmation popup/window in.
459  */
460 void wm_quit_with_optional_confirmation_prompt(bContext *C, wmWindow *win)
461 {
462         wmWindowManager *wm = CTX_wm_manager(C);
463         wmWindow *win_ctx = CTX_wm_window(C);
464
465         /* The popup will be displayed in the context window which may not be set
466          * here (this function gets called outside of normal event handling loop). */
467         CTX_wm_window_set(C, win);
468
469         if ((U.uiflag & USER_QUIT_PROMPT) && !wm->file_saved && !G.background) {
470                 wm_confirm_quit(C);
471         }
472         else {
473                 wm_exit_schedule_delayed(C);
474         }
475
476         CTX_wm_window_set(C, win_ctx);
477 }
478
479 /** \} */
480
481 /* this is event from ghost, or exit-blender op */
482 void wm_window_close(bContext *C, wmWindowManager *wm, wmWindow *win)
483 {
484         /* First check if there is another main window remaining. */
485         wmWindow *win_other;
486         for (win_other = wm->windows.first; win_other; win_other = win_other->next) {
487                 if (win_other != win &&
488                     win_other->parent == NULL &&
489                     !WM_window_is_temp_screen(win_other))
490                 {
491                         break;
492                 }
493         }
494
495         if (win->parent == NULL && win_other == NULL) {
496                 wm_quit_with_optional_confirmation_prompt(C, win);
497                 return;
498         }
499
500         /* close child windows */
501         for (wmWindow *win_child = wm->windows.first; win_child; win_child = win_child->next) {
502                 if (win_child->parent == win) {
503                         wm_window_close(C, wm, win_child);
504                 }
505         }
506
507         bScreen *screen = WM_window_get_active_screen(win);
508         WorkSpace *workspace = WM_window_get_active_workspace(win);
509         WorkSpaceLayout *layout = BKE_workspace_active_layout_get(win->workspace_hook);
510
511         BLI_remlink(&wm->windows, win);
512
513         CTX_wm_window_set(C, win);  /* needed by handlers */
514         WM_event_remove_handlers(C, &win->handlers);
515         WM_event_remove_handlers(C, &win->modalhandlers);
516
517         /* for regular use this will _never_ be NULL,
518          * however we may be freeing an improperly initialized window. */
519         if (screen) {
520                 ED_screen_exit(C, win, screen);
521         }
522
523         wm_window_free(C, wm, win);
524
525         /* if temp screen, delete it after window free (it stops jobs that can access it) */
526         if (screen && screen->temp) {
527                 Main *bmain = CTX_data_main(C);
528
529                 BLI_assert(BKE_workspace_layout_screen_get(layout) == screen);
530                 BKE_workspace_layout_remove(bmain, workspace, layout);
531         }
532 }
533
534 void wm_window_title(wmWindowManager *wm, wmWindow *win)
535 {
536         if (WM_window_is_temp_screen(win)) {
537                 /* nothing to do for 'temp' windows,
538                  * because WM_window_open_temp always sets window title  */
539         }
540         else if (win->ghostwin) {
541                 /* this is set to 1 if you don't have startup.blend open */
542                 if (G.save_over && BKE_main_blendfile_path_from_global()[0]) {
543                         char str[sizeof(((Main *)NULL)->name) + 24];
544                         BLI_snprintf(str, sizeof(str), "Blender%s [%s%s]", wm->file_saved ? "" : "*",
545                                      BKE_main_blendfile_path_from_global(),
546                                      G_MAIN->recovered ? " (Recovered)" : "");
547                         GHOST_SetTitle(win->ghostwin, str);
548                 }
549                 else
550                         GHOST_SetTitle(win->ghostwin, "Blender");
551
552                 /* Informs GHOST of unsaved changes, to set window modified visual indicator (MAC OS X)
553                  * and to give hint of unsaved changes for a user warning mechanism
554                  * in case of OS application terminate request (e.g. OS Shortcut Alt+F4, Cmd+Q, (...), or session end) */
555                 GHOST_SetWindowModifiedState(win->ghostwin, (GHOST_TUns8) !wm->file_saved);
556
557         }
558 }
559
560 void WM_window_set_dpi(wmWindow *win)
561 {
562         float auto_dpi = GHOST_GetDPIHint(win->ghostwin);
563
564         /* Clamp auto DPI to 96, since our font/interface drawing does not work well
565          * with lower sizes. The main case we are interested in supporting is higher
566          * DPI. If a smaller UI is desired it is still possible to adjust UI scale. */
567         auto_dpi = max_ff(auto_dpi, 96.0f);
568
569         /* Lazily init UI scale size, preserving backwards compatibility by
570          * computing UI scale from ratio of previous DPI and auto DPI */
571         if (U.ui_scale == 0) {
572                 int virtual_pixel = (U.virtual_pixel == VIRTUAL_PIXEL_NATIVE) ? 1 : 2;
573
574                 if (U.dpi == 0) {
575                         U.ui_scale = virtual_pixel;
576                 }
577                 else {
578                         U.ui_scale = (virtual_pixel * U.dpi * 96.0f) / (auto_dpi * 72.0f);
579                 }
580
581                 CLAMP(U.ui_scale, 0.25f, 4.0f);
582         }
583
584         /* Blender's UI drawing assumes DPI 72 as a good default following macOS
585          * while Windows and Linux use DPI 96. GHOST assumes a default 96 so we
586          * remap the DPI to Blender's convention. */
587         auto_dpi *= GHOST_GetNativePixelSize(win->ghostwin);
588         int dpi = auto_dpi * U.ui_scale * (72.0 / 96.0f);
589
590         /* Automatically set larger pixel size for high DPI. */
591         int pixelsize = max_ii(1, (int)(dpi / 64));
592         /* User adjustment for pixel size. */
593         pixelsize = max_ii(1, pixelsize + U.ui_line_width);
594
595         /* Set user preferences globals for drawing, and for forward compatibility. */
596         U.pixelsize = pixelsize;
597         U.dpi = dpi / pixelsize;
598         U.virtual_pixel = (pixelsize == 1) ? VIRTUAL_PIXEL_NATIVE : VIRTUAL_PIXEL_DOUBLE;
599         U.widget_unit = (U.pixelsize * U.dpi * 20 + 36) / 72;
600         U.dpi_fac = ((U.pixelsize * (float)U.dpi) / 72.0f);
601
602         /* update font drawing */
603         BLF_default_dpi(U.pixelsize * U.dpi);
604 }
605
606 static void wm_window_ensure_eventstate(wmWindow *win)
607 {
608         if (win->eventstate) {
609                 return;
610         }
611
612         win->eventstate = MEM_callocN(sizeof(wmEvent), "window event state");
613         wm_get_cursor_position(win, &win->eventstate->x, &win->eventstate->y);
614 }
615
616 /* belongs to below */
617 static void wm_window_ghostwindow_add(wmWindowManager *wm, const char *title, wmWindow *win)
618 {
619         GHOST_WindowHandle ghostwin;
620         GHOST_GLSettings glSettings = {0};
621         int scr_w, scr_h, posy;
622
623         /* a new window is created when pageflip mode is required for a window */
624         if (win->stereo3d_format->display_mode == S3D_DISPLAY_PAGEFLIP)
625                 glSettings.flags |= GHOST_glStereoVisual;
626
627         if (G.debug & G_DEBUG_GPU) {
628                 glSettings.flags |= GHOST_glDebugContext;
629         }
630
631         wm_get_screensize(&scr_w, &scr_h);
632         posy = (scr_h - win->posy - win->sizey);
633
634         ghostwin = GHOST_CreateWindow(g_system, title,
635                                       win->posx, posy, win->sizex, win->sizey,
636                                       (GHOST_TWindowState)win->windowstate,
637                                       GHOST_kDrawingContextTypeOpenGL,
638                                       glSettings);
639
640         if (ghostwin) {
641                 GHOST_RectangleHandle bounds;
642
643                 /* Clear drawable so we can set the new window. */
644                 wm_window_clear_drawable(wm);
645
646                 win->gpuctx = GPU_context_create();
647
648                 /* needed so we can detect the graphics card below */
649                 GPU_init();
650
651                 /* Set window as drawable upon creation. Note this has already been
652                  * it has already been activated by GHOST_CreateWindow. */
653                 bool activate = false;
654                 wm_window_set_drawable(wm, win, activate);
655
656                 win->ghostwin = ghostwin;
657                 GHOST_SetWindowUserData(ghostwin, win); /* pointer back */
658
659                 wm_window_ensure_eventstate(win);
660
661                 /* store actual window size in blender window */
662                 bounds = GHOST_GetClientBounds(win->ghostwin);
663
664                 /* win32: gives undefined window size when minimized */
665                 if (GHOST_GetWindowState(win->ghostwin) != GHOST_kWindowStateMinimized) {
666                         win->sizex = GHOST_GetWidthRectangle(bounds);
667                         win->sizey = GHOST_GetHeightRectangle(bounds);
668                 }
669                 GHOST_DisposeRectangle(bounds);
670
671 #ifndef __APPLE__
672                 /* set the state here, so minimized state comes up correct on windows */
673                 GHOST_SetWindowState(ghostwin, (GHOST_TWindowState)win->windowstate);
674 #endif
675                 /* until screens get drawn, make it nice gray */
676                 glClearColor(0.55, 0.55, 0.55, 0.0);
677                 /* Crash on OSS ATI: bugs.launchpad.net/ubuntu/+source/mesa/+bug/656100 */
678                 if (!GPU_type_matches(GPU_DEVICE_ATI, GPU_OS_UNIX, GPU_DRIVER_OPENSOURCE)) {
679                         glClear(GL_COLOR_BUFFER_BIT);
680                 }
681
682                 /* needed here, because it's used before it reads userdef */
683                 WM_window_set_dpi(win);
684
685                 wm_window_swap_buffers(win);
686
687                 //GHOST_SetWindowState(ghostwin, GHOST_kWindowStateModified);
688
689                 /* standard state vars for window */
690                 GPU_state_init();
691         }
692 }
693
694 /**
695  * Initialize #wmWindow without ghostwin, open these and clear.
696  *
697  * window size is read from window, if 0 it uses prefsize
698  * called in #WM_check, also inits stuff after file read.
699  *
700  * \warning
701  * After running, 'win->ghostwin' can be NULL in rare cases
702  * (where OpenGL driver fails to create a context for eg).
703  * We could remove them with #wm_window_ghostwindows_remove_invalid
704  * but better not since caller may continue to use.
705  * Instead, caller needs to handle the error case and cleanup.
706  */
707 void wm_window_ghostwindows_ensure(wmWindowManager *wm)
708 {
709         wmKeyMap *keymap;
710         wmWindow *win;
711
712         BLI_assert(G.background == false);
713
714         /* no commandline prefsize? then we set this.
715          * Note that these values will be used only
716          * when there is no startup.blend yet.
717          */
718         if (wm_init_state.size_x == 0) {
719                 wm_get_screensize(&wm_init_state.size_x, &wm_init_state.size_y);
720
721                 /* note!, this isnt quite correct, active screen maybe offset 1000s if PX,
722                  * we'd need a wm_get_screensize like function that gives offset,
723                  * in practice the window manager will likely move to the correct monitor */
724                 wm_init_state.start_x = 0;
725                 wm_init_state.start_y = 0;
726
727 #ifdef WITH_X11 /* X11 */
728                 /* X11, start maximized but use default sane size */
729                 wm_init_state.size_x = min_ii(wm_init_state.size_x, WM_WIN_INIT_SIZE_X);
730                 wm_init_state.size_y = min_ii(wm_init_state.size_y, WM_WIN_INIT_SIZE_Y);
731                 /* pad */
732                 wm_init_state.start_x = WM_WIN_INIT_PAD;
733                 wm_init_state.start_y = WM_WIN_INIT_PAD;
734                 wm_init_state.size_x -= WM_WIN_INIT_PAD * 2;
735                 wm_init_state.size_y -= WM_WIN_INIT_PAD * 2;
736 #endif
737         }
738
739         for (win = wm->windows.first; win; win = win->next) {
740                 if (win->ghostwin == NULL) {
741                         if ((win->sizex == 0) || (wm_init_state.override_flag & WIN_OVERRIDE_GEOM)) {
742                                 win->posx = wm_init_state.start_x;
743                                 win->posy = wm_init_state.start_y;
744                                 win->sizex = wm_init_state.size_x;
745                                 win->sizey = wm_init_state.size_y;
746
747                                 win->windowstate = GHOST_kWindowStateNormal;
748                                 wm_init_state.override_flag &= ~WIN_OVERRIDE_GEOM;
749                         }
750
751                         if (wm_init_state.override_flag & WIN_OVERRIDE_WINSTATE) {
752                                 win->windowstate = wm_init_state.windowstate;
753                                 wm_init_state.override_flag &= ~WIN_OVERRIDE_WINSTATE;
754                         }
755
756                         /* without this, cursor restore may fail, T45456 */
757                         if (win->cursor == 0) {
758                                 win->cursor = CURSOR_STD;
759                         }
760
761                         wm_window_ghostwindow_add(wm, "Blender", win);
762                 }
763                 /* happens after fileread */
764                 wm_window_ensure_eventstate(win);
765
766                 /* add keymap handlers (1 handler for all keys in map!) */
767                 keymap = WM_keymap_find(wm->defaultconf, "Window", 0, 0);
768                 WM_event_add_keymap_handler(&win->handlers, keymap);
769
770                 keymap = WM_keymap_find(wm->defaultconf, "Screen", 0, 0);
771                 WM_event_add_keymap_handler(&win->handlers, keymap);
772
773                 keymap = WM_keymap_find(wm->defaultconf, "Screen Editing", 0, 0);
774                 WM_event_add_keymap_handler(&win->modalhandlers, keymap);
775
776                 /* add drop boxes */
777                 {
778                         ListBase *lb = WM_dropboxmap_find("Window", 0, 0);
779                         WM_event_add_dropbox_handler(&win->handlers, lb);
780                 }
781                 wm_window_title(wm, win);
782
783                 /* add topbar */
784                 if (BLI_listbase_is_empty(&win->global_areas.areabase)) {
785                         ED_screen_global_areas_create(win);
786                 }
787         }
788 }
789
790 /**
791  * Call after #wm_window_ghostwindows_ensure or #WM_check
792  * (after loading a new file) in the unlikely event a window couldn't be created.
793  */
794 void wm_window_ghostwindows_remove_invalid(bContext *C, wmWindowManager *wm)
795 {
796         wmWindow *win, *win_next;
797
798         BLI_assert(G.background == false);
799
800         for (win = wm->windows.first; win; win = win_next) {
801                 win_next = win->next;
802                 if (win->ghostwin == NULL) {
803                         wm_window_close(C, wm, win);
804                 }
805         }
806 }
807
808 /**
809  * new window, no screen yet, but we open ghostwindow for it,
810  * also gets the window level handlers
811  * \note area-rip calls this.
812  * \return the window or NULL.
813  */
814 wmWindow *WM_window_open(bContext *C, const rcti *rect)
815 {
816         wmWindow *win_prev = CTX_wm_window(C);
817         wmWindow *win = wm_window_new(C, win_prev);
818
819         win->posx = rect->xmin;
820         win->posy = rect->ymin;
821         win->sizex = BLI_rcti_size_x(rect);
822         win->sizey = BLI_rcti_size_y(rect);
823
824         WM_check(C);
825
826         if (win->ghostwin) {
827                 return win;
828         }
829         else {
830                 wm_window_close(C, CTX_wm_manager(C), win);
831                 CTX_wm_window_set(C, win_prev);
832                 return NULL;
833         }
834 }
835
836 /**
837  * Uses `screen->temp` tag to define what to do, currently it limits
838  * to only one "temp" window for render out, preferences, filewindow, etc...
839  *
840  * \param type: WM_WINDOW_RENDER, WM_WINDOW_USERPREFS...
841  * \return the window or NULL.
842  */
843 wmWindow *WM_window_open_temp(bContext *C, int x, int y, int sizex, int sizey, int type)
844 {
845         Main *bmain = CTX_data_main(C);
846         wmWindow *win_prev = CTX_wm_window(C);
847         wmWindow *win;
848         bScreen *screen;
849         ScrArea *sa;
850         Scene *scene = CTX_data_scene(C);
851         ViewLayer *view_layer = CTX_data_view_layer(C);
852         const char *title;
853
854         /* convert to native OS window coordinates */
855         const float native_pixel_size = GHOST_GetNativePixelSize(win_prev->ghostwin);
856         x /= native_pixel_size;
857         y /= native_pixel_size;
858         sizex /= native_pixel_size;
859         sizey /= native_pixel_size;
860
861         /* calculate postition */
862         rcti rect;
863         rect.xmin = x + win_prev->posx - sizex / 2;
864         rect.ymin = y + win_prev->posy - sizey / 2;
865         rect.xmax = rect.xmin + sizex;
866         rect.ymax = rect.ymin + sizey;
867
868         /* changes rect to fit within desktop */
869         wm_window_check_position(&rect);
870
871         /* test if we have a temp screen already */
872         for (win = CTX_wm_manager(C)->windows.first; win; win = win->next)
873                 if (WM_window_is_temp_screen(win))
874                         break;
875
876         /* add new window? */
877         if (win == NULL) {
878                 win = wm_window_new(C, win_prev);
879
880                 win->posx = rect.xmin;
881                 win->posy = rect.ymin;
882         }
883
884         screen = WM_window_get_active_screen(win);
885
886         win->sizex = BLI_rcti_size_x(&rect);
887         win->sizey = BLI_rcti_size_y(&rect);
888
889         if (win->ghostwin) {
890                 wm_window_set_size(win, win->sizex, win->sizey);
891                 wm_window_raise(win);
892         }
893
894         if (WM_window_get_active_workspace(win) == NULL) {
895                 WorkSpace *workspace = WM_window_get_active_workspace(win_prev);
896                 BKE_workspace_active_set(win->workspace_hook, workspace);
897         }
898
899         if (screen == NULL) {
900                 /* add new screen layout */
901                 WorkSpace *workspace = WM_window_get_active_workspace(win);
902                 WorkSpaceLayout *layout = ED_workspace_layout_add(bmain, workspace, win, "temp");
903
904                 screen = BKE_workspace_layout_screen_get(layout);
905                 WM_window_set_active_layout(win, workspace, layout);
906         }
907
908         /* Set scene and view layer to match original window. */
909         STRNCPY(win->view_layer_name, view_layer->name);
910         if (WM_window_get_active_scene(win) != scene) {
911                 ED_screen_scene_change(C, win, scene);
912         }
913
914         screen->temp = 1;
915
916         /* make window active, and validate/resize */
917         CTX_wm_window_set(C, win);
918         WM_check(C);
919
920         /* It's possible `win->ghostwin == NULL`.
921          * instead of attempting to cleanup here (in a half finished state),
922          * finish setting up the screen, then free it at the end of the function,
923          * to avoid having to take into account a partially-created window.
924          */
925
926         /* ensure it shows the right spacetype editor */
927         sa = screen->areabase.first;
928         CTX_wm_area_set(C, sa);
929
930         if (type == WM_WINDOW_RENDER) {
931                 ED_area_newspace(C, sa, SPACE_IMAGE, false);
932         }
933         else if (type == WM_WINDOW_DRIVERS) {
934                 ED_area_newspace(C, sa, SPACE_IPO, false);
935         }
936         else {
937                 ED_area_newspace(C, sa, SPACE_USERPREF, false);
938         }
939
940         ED_screen_change(C, screen);
941         ED_screen_refresh(CTX_wm_manager(C), win); /* test scale */
942
943         /* do additional setup for specific editor type */
944         if (type == WM_WINDOW_DRIVERS) {
945                 ED_drivers_editor_init(C, sa);
946         }
947
948         if (sa->spacetype == SPACE_IMAGE)
949                 title = IFACE_("Blender Render");
950         else if (ELEM(sa->spacetype, SPACE_OUTLINER, SPACE_USERPREF))
951                 title = IFACE_("Blender User Preferences");
952         else if (sa->spacetype == SPACE_FILE)
953                 title = IFACE_("Blender File View");
954         else if (sa->spacetype == SPACE_IPO)
955                 title = IFACE_("Blender Drivers Editor");
956         else
957                 title = "Blender";
958
959         if (win->ghostwin) {
960                 GHOST_SetTitle(win->ghostwin, title);
961                 return win;
962         }
963         else {
964                 /* very unlikely! but opening a new window can fail */
965                 wm_window_close(C, CTX_wm_manager(C), win);
966                 CTX_wm_window_set(C, win_prev);
967
968                 return NULL;
969         }
970 }
971
972
973 /* ****************** Operators ****************** */
974
975 int wm_window_close_exec(bContext *C, wmOperator *UNUSED(op))
976 {
977         wmWindowManager *wm = CTX_wm_manager(C);
978         wmWindow *win = CTX_wm_window(C);
979         wm_window_close(C, wm, win);
980         return OPERATOR_FINISHED;
981 }
982
983 int wm_window_new_exec(bContext *C, wmOperator *UNUSED(op))
984 {
985         wmWindow *win_src = CTX_wm_window(C);
986         bool ok;
987
988         ok = (wm_window_copy_test(C, win_src, true, true) != NULL);
989
990         return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
991 }
992
993 int wm_window_new_main_exec(bContext *C, wmOperator *UNUSED(op))
994 {
995         wmWindow *win_src = CTX_wm_window(C);
996         bool ok;
997
998         ok = (wm_window_copy_test(C, win_src, true, false) != NULL);
999
1000         return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1001 }
1002
1003 /* fullscreen operator callback */
1004 int wm_window_fullscreen_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1005 {
1006         wmWindow *window = CTX_wm_window(C);
1007         GHOST_TWindowState state;
1008
1009         if (G.background)
1010                 return OPERATOR_CANCELLED;
1011
1012         state = GHOST_GetWindowState(window->ghostwin);
1013         if (state != GHOST_kWindowStateFullScreen)
1014                 GHOST_SetWindowState(window->ghostwin, GHOST_kWindowStateFullScreen);
1015         else
1016                 GHOST_SetWindowState(window->ghostwin, GHOST_kWindowStateNormal);
1017
1018         return OPERATOR_FINISHED;
1019
1020 }
1021
1022
1023 /* ************ events *************** */
1024
1025 void wm_cursor_position_from_ghost(wmWindow *win, int *x, int *y)
1026 {
1027         float fac = GHOST_GetNativePixelSize(win->ghostwin);
1028
1029         GHOST_ScreenToClient(win->ghostwin, *x, *y, x, y);
1030         *x *= fac;
1031
1032         *y = (win->sizey - 1) - *y;
1033         *y *= fac;
1034 }
1035
1036 void wm_cursor_position_to_ghost(wmWindow *win, int *x, int *y)
1037 {
1038         float fac = GHOST_GetNativePixelSize(win->ghostwin);
1039
1040         *x /= fac;
1041         *y /= fac;
1042         *y = win->sizey - *y - 1;
1043
1044         GHOST_ClientToScreen(win->ghostwin, *x, *y, x, y);
1045 }
1046
1047 void wm_get_cursor_position(wmWindow *win, int *x, int *y)
1048 {
1049         GHOST_GetCursorPosition(g_system, x, y);
1050         wm_cursor_position_from_ghost(win, x, y);
1051 }
1052
1053 typedef enum {
1054         SHIFT    = 's',
1055         CONTROL  = 'c',
1056         ALT      = 'a',
1057         OS       = 'C'
1058 } modifierKeyType;
1059
1060 /* check if specified modifier key type is pressed */
1061 static int query_qual(modifierKeyType qual)
1062 {
1063         GHOST_TModifierKeyMask left, right;
1064         int val = 0;
1065
1066         switch (qual) {
1067                 case SHIFT:
1068                         left = GHOST_kModifierKeyLeftShift;
1069                         right = GHOST_kModifierKeyRightShift;
1070                         break;
1071                 case CONTROL:
1072                         left = GHOST_kModifierKeyLeftControl;
1073                         right = GHOST_kModifierKeyRightControl;
1074                         break;
1075                 case OS:
1076                         left = right = GHOST_kModifierKeyOS;
1077                         break;
1078                 case ALT:
1079                 default:
1080                         left = GHOST_kModifierKeyLeftAlt;
1081                         right = GHOST_kModifierKeyRightAlt;
1082                         break;
1083         }
1084
1085         GHOST_GetModifierKeyState(g_system, left, &val);
1086         if (!val)
1087                 GHOST_GetModifierKeyState(g_system, right, &val);
1088
1089         return val;
1090 }
1091
1092 static void wm_window_set_drawable(wmWindowManager *wm, wmWindow *win, bool activate)
1093 {
1094         BLI_assert(ELEM(wm->windrawable, NULL, win));
1095
1096         wm->windrawable = win;
1097         if (activate) {
1098                 GHOST_ActivateWindowDrawingContext(win->ghostwin);
1099         }
1100         GPU_context_active_set(win->gpuctx);
1101         immActivate();
1102 }
1103
1104 void wm_window_clear_drawable(wmWindowManager *wm)
1105 {
1106         if (wm->windrawable) {
1107                 BLF_batch_reset();
1108                 gpu_batch_presets_reset();
1109                 immDeactivate();
1110                 wm->windrawable = NULL;
1111         }
1112 }
1113
1114 void wm_window_make_drawable(wmWindowManager *wm, wmWindow *win)
1115 {
1116         BLI_assert(GPU_framebuffer_current_get() == 0);
1117
1118         if (win != wm->windrawable && win->ghostwin) {
1119 //              win->lmbut = 0; /* keeps hanging when mousepressed while other window opened */
1120                 wm_window_clear_drawable(wm);
1121
1122                 if (G.debug & G_DEBUG_EVENTS) {
1123                         printf("%s: set drawable %d\n", __func__, win->winid);
1124                 }
1125
1126                 wm_window_set_drawable(wm, win, true);
1127
1128                 /* this can change per window */
1129                 WM_window_set_dpi(win);
1130         }
1131 }
1132
1133 /* Reset active the current window opengl drawing context. */
1134 void wm_window_reset_drawable(void)
1135 {
1136         BLI_assert(BLI_thread_is_main());
1137         BLI_assert(GPU_framebuffer_current_get() == 0);
1138         wmWindowManager *wm = G_MAIN->wm.first;
1139
1140         if (wm == NULL)
1141                 return;
1142
1143         wmWindow *win = wm->windrawable;
1144
1145         if (win && win->ghostwin) {
1146                 wm_window_clear_drawable(wm);
1147                 wm_window_set_drawable(wm, win, true);
1148         }
1149 }
1150
1151 /* called by ghost, here we handle events for windows themselves or send to event system */
1152 /* mouse coordinate converversion happens here */
1153 static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr)
1154 {
1155         bContext *C = C_void_ptr;
1156         wmWindowManager *wm = CTX_wm_manager(C);
1157         GHOST_TEventType type = GHOST_GetEventType(evt);
1158         int time = GHOST_GetEventTime(evt);
1159
1160         if (type == GHOST_kEventQuit) {
1161                 WM_exit(C);
1162         }
1163         else {
1164                 GHOST_WindowHandle ghostwin = GHOST_GetEventWindow(evt);
1165                 GHOST_TEventDataPtr data = GHOST_GetEventData(evt);
1166                 wmWindow *win;
1167
1168                 /* Ghost now can call this function for life resizes, but it should return if WM didn't initialize yet.
1169                  * Can happen on file read (especially full size window)  */
1170                 if ((wm->initialized & WM_WINDOW_IS_INITIALIZED) == 0) {
1171                         return 1;
1172                 }
1173                 if (!ghostwin) {
1174                         /* XXX - should be checked, why are we getting an event here, and */
1175                         /* what is it? */
1176                         puts("<!> event has no window");
1177                         return 1;
1178                 }
1179                 else if (!GHOST_ValidWindow(g_system, ghostwin)) {
1180                         /* XXX - should be checked, why are we getting an event here, and */
1181                         /* what is it? */
1182                         puts("<!> event has invalid window");
1183                         return 1;
1184                 }
1185                 else {
1186                         win = GHOST_GetWindowUserData(ghostwin);
1187                 }
1188
1189                 switch (type) {
1190                         case GHOST_kEventWindowDeactivate:
1191                                 wm_event_add_ghostevent(wm, win, type, time, data);
1192                                 win->active = 0; /* XXX */
1193
1194                                 /* clear modifiers for inactive windows */
1195                                 win->eventstate->alt = 0;
1196                                 win->eventstate->ctrl = 0;
1197                                 win->eventstate->shift = 0;
1198                                 win->eventstate->oskey = 0;
1199                                 win->eventstate->keymodifier = 0;
1200
1201                                 break;
1202                         case GHOST_kEventWindowActivate:
1203                         {
1204                                 GHOST_TEventKeyData kdata;
1205                                 wmEvent event;
1206                                 int wx, wy;
1207                                 const int keymodifier = ((query_qual(SHIFT)     ? KM_SHIFT : 0) |
1208                                                          (query_qual(CONTROL)   ? KM_CTRL  : 0) |
1209                                                          (query_qual(ALT)       ? KM_ALT   : 0) |
1210                                                          (query_qual(OS)        ? KM_OSKEY : 0));
1211
1212                                 /* Win23/GHOST modifier bug, see T40317 */
1213 #ifndef WIN32
1214 //#  define USE_WIN_ACTIVATE
1215 #endif
1216
1217                                 wm->winactive = win; /* no context change! c->wm->windrawable is drawable, or for area queues */
1218
1219                                 win->active = 1;
1220 //                              window_handle(win, INPUTCHANGE, win->active);
1221
1222                                 /* bad ghost support for modifier keys... so on activate we set the modifiers again */
1223
1224                                 /* TODO: This is not correct since a modifier may be held when a window is activated...
1225                                  * better solve this at ghost level. attempted fix r54450 but it caused bug [#34255]
1226                                  *
1227                                  * For now don't send GHOST_kEventKeyDown events, just set the 'eventstate'.
1228                                  */
1229                                 kdata.ascii = '\0';
1230                                 kdata.utf8_buf[0] = '\0';
1231
1232                                 if (win->eventstate->shift) {
1233                                         if ((keymodifier & KM_SHIFT) == 0) {
1234                                                 kdata.key = GHOST_kKeyLeftShift;
1235                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
1236                                         }
1237                                 }
1238 #ifdef USE_WIN_ACTIVATE
1239                                 else {
1240                                         if (keymodifier & KM_SHIFT) {
1241                                                 win->eventstate->shift = KM_MOD_FIRST;
1242                                         }
1243                                 }
1244 #endif
1245                                 if (win->eventstate->ctrl) {
1246                                         if ((keymodifier & KM_CTRL) == 0) {
1247                                                 kdata.key = GHOST_kKeyLeftControl;
1248                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
1249                                         }
1250                                 }
1251 #ifdef USE_WIN_ACTIVATE
1252                                 else {
1253                                         if (keymodifier & KM_CTRL) {
1254                                                 win->eventstate->ctrl = KM_MOD_FIRST;
1255                                         }
1256                                 }
1257 #endif
1258                                 if (win->eventstate->alt) {
1259                                         if ((keymodifier & KM_ALT) == 0) {
1260                                                 kdata.key = GHOST_kKeyLeftAlt;
1261                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
1262                                         }
1263                                 }
1264 #ifdef USE_WIN_ACTIVATE
1265                                 else {
1266                                         if (keymodifier & KM_ALT) {
1267                                                 win->eventstate->alt = KM_MOD_FIRST;
1268                                         }
1269                                 }
1270 #endif
1271                                 if (win->eventstate->oskey) {
1272                                         if ((keymodifier & KM_OSKEY) == 0) {
1273                                                 kdata.key = GHOST_kKeyOS;
1274                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
1275                                         }
1276                                 }
1277 #ifdef USE_WIN_ACTIVATE
1278                                 else {
1279                                         if (keymodifier & KM_OSKEY) {
1280                                                 win->eventstate->oskey = KM_MOD_FIRST;
1281                                         }
1282                                 }
1283 #endif
1284
1285 #undef USE_WIN_ACTIVATE
1286
1287
1288                                 /* keymodifier zero, it hangs on hotkeys that open windows otherwise */
1289                                 win->eventstate->keymodifier = 0;
1290
1291                                 /* entering window, update mouse pos. but no event */
1292                                 wm_get_cursor_position(win,  &wx, &wy);
1293
1294                                 win->eventstate->x = wx;
1295                                 win->eventstate->y = wy;
1296
1297                                 win->addmousemove = 1;   /* enables highlighted buttons */
1298
1299                                 wm_window_make_drawable(wm, win);
1300
1301                                 /* window might be focused by mouse click in configuration of window manager
1302                                  * when focus is not following mouse
1303                                  * click could have been done on a button and depending on window manager settings
1304                                  * click would be passed to blender or not, but in any case button under cursor
1305                                  * should be activated, so at max next click on button without moving mouse
1306                                  * would trigger it's handle function
1307                                  * currently it seems to be common practice to generate new event for, but probably
1308                                  * we'll need utility function for this? (sergey)
1309                                  */
1310                                 wm_event_init_from_window(win, &event);
1311                                 event.type = MOUSEMOVE;
1312                                 event.prevx = event.x;
1313                                 event.prevy = event.y;
1314
1315                                 wm_event_add(win, &event);
1316
1317                                 break;
1318                         }
1319                         case GHOST_kEventWindowClose:
1320                         {
1321                                 wm_window_close(C, wm, win);
1322                                 break;
1323                         }
1324                         case GHOST_kEventWindowUpdate:
1325                         {
1326                                 if (G.debug & G_DEBUG_EVENTS) {
1327                                         printf("%s: ghost redraw %d\n", __func__, win->winid);
1328                                 }
1329
1330                                 wm_window_make_drawable(wm, win);
1331                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
1332
1333                                 break;
1334                         }
1335                         case GHOST_kEventWindowSize:
1336                         case GHOST_kEventWindowMove:
1337                         {
1338                                 GHOST_TWindowState state;
1339                                 state = GHOST_GetWindowState(win->ghostwin);
1340                                 win->windowstate = state;
1341
1342                                 WM_window_set_dpi(win);
1343
1344                                 /* win32: gives undefined window size when minimized */
1345                                 if (state != GHOST_kWindowStateMinimized) {
1346                                         GHOST_RectangleHandle client_rect;
1347                                         int l, t, r, b, scr_w, scr_h;
1348                                         int sizex, sizey, posx, posy;
1349
1350                                         client_rect = GHOST_GetClientBounds(win->ghostwin);
1351                                         GHOST_GetRectangle(client_rect, &l, &t, &r, &b);
1352
1353                                         GHOST_DisposeRectangle(client_rect);
1354
1355                                         wm_get_desktopsize(&scr_w, &scr_h);
1356                                         sizex = r - l;
1357                                         sizey = b - t;
1358                                         posx = l;
1359                                         posy = scr_h - t - win->sizey;
1360
1361                                         /*
1362                                          * Ghost sometimes send size or move events when the window hasn't changed.
1363                                          * One case of this is using compiz on linux. To alleviate the problem
1364                                          * we ignore all such event here.
1365                                          *
1366                                          * It might be good to eventually do that at Ghost level, but that is for
1367                                          * another time.
1368                                          */
1369                                         if (win->sizex != sizex ||
1370                                             win->sizey != sizey ||
1371                                             win->posx != posx ||
1372                                             win->posy != posy)
1373                                         {
1374                                                 const bScreen *screen = WM_window_get_active_screen(win);
1375
1376                                                 win->sizex = sizex;
1377                                                 win->sizey = sizey;
1378                                                 win->posx = posx;
1379                                                 win->posy = posy;
1380
1381                                                 /* debug prints */
1382                                                 if (G.debug & G_DEBUG_EVENTS) {
1383                                                         const char *state_str;
1384                                                         state = GHOST_GetWindowState(win->ghostwin);
1385
1386                                                         if (state == GHOST_kWindowStateNormal) {
1387                                                                 state_str = "normal";
1388                                                         }
1389                                                         else if (state == GHOST_kWindowStateMinimized) {
1390                                                                 state_str = "minimized";
1391                                                         }
1392                                                         else if (state == GHOST_kWindowStateMaximized) {
1393                                                                 state_str = "maximized";
1394                                                         }
1395                                                         else if (state == GHOST_kWindowStateFullScreen) {
1396                                                                 state_str = "fullscreen";
1397                                                         }
1398                                                         else {
1399                                                                 state_str = "<unknown>";
1400                                                         }
1401
1402                                                         printf("%s: window %d state = %s\n", __func__, win->winid, state_str);
1403
1404                                                         if (type != GHOST_kEventWindowSize) {
1405                                                                 printf("win move event pos %d %d size %d %d\n",
1406                                                                        win->posx, win->posy, win->sizex, win->sizey);
1407                                                         }
1408                                                 }
1409
1410                                                 wm_window_make_drawable(wm, win);
1411                                                 BKE_icon_changed(screen->id.icon_id);
1412                                                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1413                                                 WM_event_add_notifier(C, NC_WINDOW | NA_EDITED, NULL);
1414
1415 #if defined(__APPLE__) || defined(WIN32)
1416                                                 /* OSX and Win32 don't return to the mainloop while resize */
1417                                                 wm_event_do_notifiers(C);
1418                                                 wm_draw_update(C);
1419
1420                                                 /* Warning! code above nulls 'C->wm.window', causing BGE to quit, see: T45699.
1421                                                  * Further, its easier to match behavior across platforms, so restore the window. */
1422                                                 CTX_wm_window_set(C, win);
1423 #endif
1424                                         }
1425                                 }
1426                                 break;
1427                         }
1428
1429                         case GHOST_kEventWindowDPIHintChanged:
1430                         {
1431                                 WM_window_set_dpi(win);
1432                                 /* font's are stored at each DPI level, without this we can easy load 100's of fonts */
1433                                 BLF_cache_clear();
1434
1435                                 WM_main_add_notifier(NC_WINDOW, NULL);      /* full redraw */
1436                                 WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL);    /* refresh region sizes */
1437                                 break;
1438                         }
1439
1440                         case GHOST_kEventOpenMainFile:
1441                         {
1442                                 PointerRNA props_ptr;
1443                                 wmWindow *oldWindow;
1444                                 const char *path = GHOST_GetEventData(evt);
1445
1446                                 if (path) {
1447                                         wmOperatorType *ot = WM_operatortype_find("WM_OT_open_mainfile", false);
1448                                         /* operator needs a valid window in context, ensures
1449                                          * it is correctly set */
1450                                         oldWindow = CTX_wm_window(C);
1451                                         CTX_wm_window_set(C, win);
1452
1453                                         WM_operator_properties_create_ptr(&props_ptr, ot);
1454                                         RNA_string_set(&props_ptr, "filepath", path);
1455                                         WM_operator_name_call_ptr(C, ot, WM_OP_EXEC_DEFAULT, &props_ptr);
1456                                         WM_operator_properties_free(&props_ptr);
1457
1458                                         CTX_wm_window_set(C, oldWindow);
1459                                 }
1460                                 break;
1461                         }
1462                         case GHOST_kEventDraggingDropDone:
1463                         {
1464                                 wmEvent event;
1465                                 GHOST_TEventDragnDropData *ddd = GHOST_GetEventData(evt);
1466                                 int wx, wy;
1467
1468                                 /* entering window, update mouse pos */
1469                                 wm_get_cursor_position(win, &wx, &wy);
1470                                 win->eventstate->x = wx;
1471                                 win->eventstate->y = wy;
1472
1473                                 wm_event_init_from_window(win, &event);  /* copy last state, like mouse coords */
1474
1475                                 /* activate region */
1476                                 event.type = MOUSEMOVE;
1477                                 event.prevx = event.x;
1478                                 event.prevy = event.y;
1479
1480                                 wm->winactive = win; /* no context change! c->wm->windrawable is drawable, or for area queues */
1481                                 win->active = 1;
1482
1483                                 wm_event_add(win, &event);
1484
1485
1486                                 /* make blender drop event with custom data pointing to wm drags */
1487                                 event.type = EVT_DROP;
1488                                 event.val = KM_RELEASE;
1489                                 event.custom = EVT_DATA_DRAGDROP;
1490                                 event.customdata = &wm->drags;
1491                                 event.customdatafree = 1;
1492
1493                                 wm_event_add(win, &event);
1494
1495                                 /* printf("Drop detected\n"); */
1496
1497                                 /* add drag data to wm for paths: */
1498
1499                                 if (ddd->dataType == GHOST_kDragnDropTypeFilenames) {
1500                                         GHOST_TStringArray *stra = ddd->data;
1501                                         int a, icon;
1502
1503                                         for (a = 0; a < stra->count; a++) {
1504                                                 printf("drop file %s\n", stra->strings[a]);
1505                                                 /* try to get icon type from extension */
1506                                                 icon = ED_file_extension_icon((char *)stra->strings[a]);
1507
1508                                                 WM_event_start_drag(C, icon, WM_DRAG_PATH, stra->strings[a], 0.0, WM_DRAG_NOP);
1509                                                 /* void poin should point to string, it makes a copy */
1510                                                 break; /* only one drop element supported now */
1511                                         }
1512                                 }
1513
1514                                 break;
1515                         }
1516                         case GHOST_kEventNativeResolutionChange:
1517                         {
1518                                 // only update if the actual pixel size changes
1519                                 float prev_pixelsize = U.pixelsize;
1520                                 WM_window_set_dpi(win);
1521
1522                                 if (U.pixelsize != prev_pixelsize) {
1523                                         BKE_icon_changed(WM_window_get_active_screen(win)->id.icon_id);
1524
1525                                         // close all popups since they are positioned with the pixel
1526                                         // size baked in and it's difficult to correct them
1527                                         wmWindow *oldWindow = CTX_wm_window(C);
1528                                         CTX_wm_window_set(C, win);
1529                                         UI_popup_handlers_remove_all(C, &win->modalhandlers);
1530                                         CTX_wm_window_set(C, oldWindow);
1531
1532                                         wm_window_make_drawable(wm, win);
1533
1534                                         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1535                                         WM_event_add_notifier(C, NC_WINDOW | NA_EDITED, NULL);
1536                                 }
1537
1538                                 break;
1539                         }
1540                         case GHOST_kEventTrackpad:
1541                         {
1542                                 GHOST_TEventTrackpadData *pd = data;
1543
1544                                 wm_cursor_position_from_ghost(win, &pd->x, &pd->y);
1545                                 wm_event_add_ghostevent(wm, win, type, time, data);
1546                                 break;
1547                         }
1548                         case GHOST_kEventCursorMove:
1549                         {
1550                                 GHOST_TEventCursorData *cd = data;
1551
1552                                 wm_cursor_position_from_ghost(win, &cd->x, &cd->y);
1553                                 wm_event_add_ghostevent(wm, win, type, time, data);
1554                                 break;
1555                         }
1556                         default:
1557                                 wm_event_add_ghostevent(wm, win, type, time, data);
1558                                 break;
1559                 }
1560
1561         }
1562         return 1;
1563 }
1564
1565
1566 /**
1567  * This timer system only gives maximum 1 timer event per redraw cycle,
1568  * to prevent queues to get overloaded.
1569  * Timer handlers should check for delta to decide if they just update, or follow real time.
1570  * Timer handlers can also set duration to match frames passed
1571  */
1572 static int wm_window_timer(const bContext *C)
1573 {
1574         wmWindowManager *wm = CTX_wm_manager(C);
1575         wmTimer *wt, *wtnext;
1576         wmWindow *win;
1577         double time = PIL_check_seconds_timer();
1578         int retval = 0;
1579
1580         for (wt = wm->timers.first; wt; wt = wtnext) {
1581                 wtnext = wt->next; /* in case timer gets removed */
1582                 win = wt->win;
1583
1584                 if (wt->sleep == 0) {
1585                         if (time > wt->ntime) {
1586                                 wt->delta = time - wt->ltime;
1587                                 wt->duration += wt->delta;
1588                                 wt->ltime = time;
1589                                 wt->ntime = wt->stime + wt->timestep * ceil(wt->duration / wt->timestep);
1590
1591                                 if (wt->event_type == TIMERJOBS)
1592                                         wm_jobs_timer(C, wm, wt);
1593                                 else if (wt->event_type == TIMERAUTOSAVE)
1594                                         wm_autosave_timer(C, wm, wt);
1595                                 else if (wt->event_type == TIMERNOTIFIER)
1596                                         WM_main_add_notifier(GET_UINT_FROM_POINTER(wt->customdata), NULL);
1597                                 else if (win) {
1598                                         wmEvent event;
1599                                         wm_event_init_from_window(win, &event);
1600
1601                                         event.type = wt->event_type;
1602                                         event.val = KM_NOTHING;
1603                                         event.keymodifier = 0;
1604                                         event.custom = EVT_DATA_TIMER;
1605                                         event.customdata = wt;
1606                                         wm_event_add(win, &event);
1607
1608                                         retval = 1;
1609                                 }
1610                         }
1611                 }
1612         }
1613         return retval;
1614 }
1615
1616 void wm_window_process_events(const bContext *C)
1617 {
1618         int hasevent;
1619
1620         BLI_assert(BLI_thread_is_main());
1621
1622         hasevent = GHOST_ProcessEvents(g_system, 0); /* 0 is no wait */
1623
1624         if (hasevent)
1625                 GHOST_DispatchEvents(g_system);
1626
1627         hasevent |= wm_window_timer(C);
1628
1629         /* no event, we sleep 5 milliseconds */
1630         if (hasevent == 0)
1631                 PIL_sleep_ms(5);
1632 }
1633
1634 void wm_window_process_events_nosleep(void)
1635 {
1636         if (GHOST_ProcessEvents(g_system, 0))
1637                 GHOST_DispatchEvents(g_system);
1638 }
1639
1640 /* exported as handle callback to bke blender.c */
1641 void wm_window_testbreak(void)
1642 {
1643         static double ltime = 0;
1644         double curtime = PIL_check_seconds_timer();
1645
1646         BLI_assert(BLI_thread_is_main());
1647
1648         /* only check for breaks every 50 milliseconds
1649          * if we get called more often.
1650          */
1651         if ((curtime - ltime) > 0.05) {
1652                 int hasevent = GHOST_ProcessEvents(g_system, 0); /* 0 is no wait */
1653
1654                 if (hasevent)
1655                         GHOST_DispatchEvents(g_system);
1656
1657                 ltime = curtime;
1658         }
1659 }
1660
1661 /* **************** init ********************** */
1662
1663 /* bContext can be null in background mode because we don't
1664  * need to event handling. */
1665 void wm_ghost_init(bContext *C)
1666 {
1667         if (!g_system) {
1668                 GHOST_EventConsumerHandle consumer;
1669
1670                 if (C != NULL) {
1671                         consumer = GHOST_CreateEventConsumer(ghost_event_proc, C);
1672                 }
1673
1674                 g_system = GHOST_CreateSystem();
1675
1676                 if (C != NULL) {
1677                         GHOST_AddEventConsumer(g_system, consumer);
1678                 }
1679
1680                 if (wm_init_state.native_pixels) {
1681                         GHOST_UseNativePixels();
1682                 }
1683         }
1684 }
1685
1686 void wm_ghost_exit(void)
1687 {
1688         if (g_system)
1689                 GHOST_DisposeSystem(g_system);
1690
1691         g_system = NULL;
1692 }
1693
1694 /* **************** timer ********************** */
1695
1696 /* to (de)activate running timers temporary */
1697 void WM_event_timer_sleep(wmWindowManager *wm, wmWindow *UNUSED(win), wmTimer *timer, bool do_sleep)
1698 {
1699         wmTimer *wt;
1700
1701         for (wt = wm->timers.first; wt; wt = wt->next)
1702                 if (wt == timer)
1703                         break;
1704
1705         if (wt)
1706                 wt->sleep = do_sleep;
1707 }
1708
1709 wmTimer *WM_event_add_timer(wmWindowManager *wm, wmWindow *win, int event_type, double timestep)
1710 {
1711         wmTimer *wt = MEM_callocN(sizeof(wmTimer), "window timer");
1712
1713         wt->event_type = event_type;
1714         wt->ltime = PIL_check_seconds_timer();
1715         wt->ntime = wt->ltime + timestep;
1716         wt->stime = wt->ltime;
1717         wt->timestep = timestep;
1718         wt->win = win;
1719
1720         BLI_addtail(&wm->timers, wt);
1721
1722         return wt;
1723 }
1724
1725 wmTimer *WM_event_add_timer_notifier(wmWindowManager *wm, wmWindow *win, unsigned int type, double timestep)
1726 {
1727         wmTimer *wt = MEM_callocN(sizeof(wmTimer), "window timer");
1728
1729         wt->event_type = TIMERNOTIFIER;
1730         wt->ltime = PIL_check_seconds_timer();
1731         wt->ntime = wt->ltime + timestep;
1732         wt->stime = wt->ltime;
1733         wt->timestep = timestep;
1734         wt->win = win;
1735         wt->customdata = SET_UINT_IN_POINTER(type);
1736         wt->flags |= WM_TIMER_NO_FREE_CUSTOM_DATA;
1737
1738         BLI_addtail(&wm->timers, wt);
1739
1740         return wt;
1741 }
1742
1743 void WM_event_remove_timer(wmWindowManager *wm, wmWindow *UNUSED(win), wmTimer *timer)
1744 {
1745         wmTimer *wt;
1746
1747         /* extra security check */
1748         for (wt = wm->timers.first; wt; wt = wt->next)
1749                 if (wt == timer)
1750                         break;
1751         if (wt) {
1752                 wmWindow *win;
1753
1754                 if (wm->reports.reporttimer == wt)
1755                         wm->reports.reporttimer = NULL;
1756
1757                 BLI_remlink(&wm->timers, wt);
1758                 if (wt->customdata != NULL && (wt->flags & WM_TIMER_NO_FREE_CUSTOM_DATA) == 0) {
1759                         MEM_freeN(wt->customdata);
1760                 }
1761                 MEM_freeN(wt);
1762
1763                 /* there might be events in queue with this timer as customdata */
1764                 for (win = wm->windows.first; win; win = win->next) {
1765                         wmEvent *event;
1766                         for (event = win->queue.first; event; event = event->next) {
1767                                 if (event->customdata == wt) {
1768                                         event->customdata = NULL;
1769                                         event->type = EVENT_NONE;       /* timer users customdata, dont want NULL == NULL */
1770                                 }
1771                         }
1772                 }
1773         }
1774 }
1775
1776 void WM_event_remove_timer_notifier(wmWindowManager *wm, wmWindow *win, wmTimer *timer)
1777 {
1778         timer->customdata = NULL;
1779         WM_event_remove_timer(wm, win, timer);
1780 }
1781
1782 /* ******************* clipboard **************** */
1783
1784 static char *wm_clipboard_text_get_ex(bool selection, int *r_len,
1785                                       bool firstline)
1786 {
1787         char *p, *p2, *buf, *newbuf;
1788
1789         if (G.background) {
1790                 *r_len = 0;
1791                 return NULL;
1792         }
1793
1794         buf = (char *)GHOST_getClipboard(selection);
1795         if (!buf) {
1796                 *r_len = 0;
1797                 return NULL;
1798         }
1799
1800         /* always convert from \r\n to \n */
1801         p2 = newbuf = MEM_mallocN(strlen(buf) + 1, __func__);
1802
1803         if (firstline) {
1804                 /* will return an over-alloc'ed value in the case there are newlines */
1805                 for (p = buf; *p; p++) {
1806                         if ((*p != '\n') && (*p != '\r')) {
1807                                 *(p2++) = *p;
1808                         }
1809                         else {
1810                                 break;
1811                         }
1812                 }
1813         }
1814         else {
1815                 for (p = buf; *p; p++) {
1816                         if (*p != '\r') {
1817                                 *(p2++) = *p;
1818                         }
1819                 }
1820         }
1821
1822         *p2 = '\0';
1823
1824         free(buf); /* ghost uses regular malloc */
1825
1826         *r_len = (p2 - newbuf);
1827
1828         return newbuf;
1829 }
1830
1831 /**
1832  * Return text from the clipboard.
1833  *
1834  * \note Caller needs to check for valid utf8 if this is a requirement.
1835  */
1836 char *WM_clipboard_text_get(bool selection, int *r_len)
1837 {
1838         return wm_clipboard_text_get_ex(selection, r_len, false);
1839 }
1840
1841 /**
1842  * Convenience function for pasting to areas of Blender which don't support newlines.
1843  */
1844 char *WM_clipboard_text_get_firstline(bool selection, int *r_len)
1845 {
1846         return wm_clipboard_text_get_ex(selection, r_len, true);
1847 }
1848
1849 void WM_clipboard_text_set(const char *buf, bool selection)
1850 {
1851         if (!G.background) {
1852 #ifdef _WIN32
1853                 /* do conversion from \n to \r\n on Windows */
1854                 const char *p;
1855                 char *p2, *newbuf;
1856                 int newlen = 0;
1857
1858                 for (p = buf; *p; p++) {
1859                         if (*p == '\n')
1860                                 newlen += 2;
1861                         else
1862                                 newlen++;
1863                 }
1864
1865                 newbuf = MEM_callocN(newlen + 1, "WM_clipboard_text_set");
1866
1867                 for (p = buf, p2 = newbuf; *p; p++, p2++) {
1868                         if (*p == '\n') {
1869                                 *(p2++) = '\r'; *p2 = '\n';
1870                         }
1871                         else {
1872                                 *p2 = *p;
1873                         }
1874                 }
1875                 *p2 = '\0';
1876
1877                 GHOST_putClipboard((GHOST_TInt8 *)newbuf, selection);
1878                 MEM_freeN(newbuf);
1879 #else
1880                 GHOST_putClipboard((GHOST_TInt8 *)buf, selection);
1881 #endif
1882         }
1883 }
1884
1885 /* ******************* progress bar **************** */
1886
1887 void WM_progress_set(wmWindow *win, float progress)
1888 {
1889         GHOST_SetProgressBar(win->ghostwin, progress);
1890 }
1891
1892 void WM_progress_clear(wmWindow *win)
1893 {
1894         GHOST_EndProgressBar(win->ghostwin);
1895 }
1896
1897 /* ************************************ */
1898
1899 void wm_window_get_position(wmWindow *win, int *r_pos_x, int *r_pos_y)
1900 {
1901         *r_pos_x = win->posx;
1902         *r_pos_y = win->posy;
1903 }
1904
1905 void wm_window_set_size(wmWindow *win, int width, int height)
1906 {
1907         GHOST_SetClientSize(win->ghostwin, width, height);
1908 }
1909
1910 void wm_window_lower(wmWindow *win)
1911 {
1912         GHOST_SetWindowOrder(win->ghostwin, GHOST_kWindowOrderBottom);
1913 }
1914
1915 void wm_window_raise(wmWindow *win)
1916 {
1917         GHOST_SetWindowOrder(win->ghostwin, GHOST_kWindowOrderTop);
1918 }
1919
1920 void wm_window_swap_buffers(wmWindow *win)
1921 {
1922         GHOST_SwapWindowBuffers(win->ghostwin);
1923 }
1924
1925 void wm_window_set_swap_interval (wmWindow *win, int interval)
1926 {
1927         GHOST_SetSwapInterval(win->ghostwin, interval);
1928 }
1929
1930 bool wm_window_get_swap_interval(wmWindow *win, int *intervalOut)
1931 {
1932         return GHOST_GetSwapInterval(win->ghostwin, intervalOut);
1933 }
1934
1935
1936 /* ******************* exported api ***************** */
1937
1938
1939 /* called whem no ghost system was initialized */
1940 void WM_init_state_size_set(int stax, int stay, int sizx, int sizy)
1941 {
1942         wm_init_state.start_x = stax; /* left hand pos */
1943         wm_init_state.start_y = stay; /* bottom pos */
1944         wm_init_state.size_x = sizx < 640 ? 640 : sizx;
1945         wm_init_state.size_y = sizy < 480 ? 480 : sizy;
1946         wm_init_state.override_flag |= WIN_OVERRIDE_GEOM;
1947 }
1948
1949 /* for borderless and border windows set from command-line */
1950 void WM_init_state_fullscreen_set(void)
1951 {
1952         wm_init_state.windowstate = GHOST_kWindowStateFullScreen;
1953         wm_init_state.override_flag |= WIN_OVERRIDE_WINSTATE;
1954 }
1955
1956 void WM_init_state_normal_set(void)
1957 {
1958         wm_init_state.windowstate = GHOST_kWindowStateNormal;
1959         wm_init_state.override_flag |= WIN_OVERRIDE_WINSTATE;
1960 }
1961
1962 void WM_init_native_pixels(bool do_it)
1963 {
1964         wm_init_state.native_pixels = do_it;
1965 }
1966
1967 /* This function requires access to the GHOST_SystemHandle (g_system) */
1968 void WM_cursor_warp(wmWindow *win, int x, int y)
1969 {
1970         if (win && win->ghostwin) {
1971                 int oldx = x, oldy = y;
1972
1973                 wm_cursor_position_to_ghost(win, &x, &y);
1974                 GHOST_SetCursorPosition(g_system, x, y);
1975
1976                 win->eventstate->prevx = oldx;
1977                 win->eventstate->prevy = oldy;
1978
1979                 win->eventstate->x = oldx;
1980                 win->eventstate->y = oldy;
1981         }
1982 }
1983
1984 /**
1985  * Set x, y to values we can actually position the cursor to.
1986  */
1987 void WM_cursor_compatible_xy(wmWindow *win, int *x, int *y)
1988 {
1989         float f = GHOST_GetNativePixelSize(win->ghostwin);
1990         if (f != 1.0f) {
1991                 *x = (int)(*x / f) * f;
1992                 *y = (int)(*y / f) * f;
1993         }
1994 }
1995
1996 /**
1997  * Get the cursor pressure, in most cases you'll want to use wmTabletData from the event
1998  */
1999 float WM_cursor_pressure(const struct wmWindow *win)
2000 {
2001         const GHOST_TabletData *td = GHOST_GetTabletData(win->ghostwin);
2002         /* if there's tablet data from an active tablet device then add it */
2003         if ((td != NULL) && td->Active != GHOST_kTabletModeNone) {
2004                 return td->Pressure;
2005         }
2006         else {
2007                 return -1.0f;
2008         }
2009 }
2010
2011 /* support for native pixel size */
2012 /* mac retina opens window in size X, but it has up to 2 x more pixels */
2013 int WM_window_pixels_x(const wmWindow *win)
2014 {
2015         float f = GHOST_GetNativePixelSize(win->ghostwin);
2016
2017         return (int)(f * (float)win->sizex);
2018 }
2019 int WM_window_pixels_y(const wmWindow *win)
2020 {
2021         float f = GHOST_GetNativePixelSize(win->ghostwin);
2022
2023         return (int)(f * (float)win->sizey);
2024 }
2025
2026 /**
2027  * Get boundaries usable by all window contents, including global areas.
2028  */
2029 void WM_window_rect_calc(const wmWindow *win, rcti *r_rect)
2030 {
2031         BLI_rcti_init(r_rect, 0, WM_window_pixels_x(win), 0, WM_window_pixels_y(win));
2032 }
2033 /**
2034  * Get boundaries usable by screen-layouts, excluding global areas.
2035  * \note Depends on U.dpi_fac. Should that be outdated, call #WM_window_set_dpi first.
2036  */
2037 void WM_window_screen_rect_calc(const wmWindow *win, rcti *r_rect)
2038 {
2039         rcti window_rect, screen_rect;
2040
2041         WM_window_rect_calc(win, &window_rect);
2042         screen_rect = window_rect;
2043
2044         /* Substract global areas from screen rectangle. */
2045         for (ScrArea *global_area = win->global_areas.areabase.first; global_area; global_area = global_area->next) {
2046                 int height = ED_area_global_size_y(global_area) - 1;
2047
2048                 if (global_area->global->flag & GLOBAL_AREA_IS_HIDDEN) {
2049                         continue;
2050                 }
2051
2052                 switch (global_area->global->align) {
2053                         case GLOBAL_AREA_ALIGN_TOP:
2054                                 if ((screen_rect.ymax - height) > window_rect.ymin) {
2055                                         height += U.pixelsize;
2056                                 }
2057                                 if (screen_rect.ymax < (window_rect.ymax - 1)) {
2058                                         height += U.pixelsize;
2059                                 }
2060                                 screen_rect.ymax -= height;
2061                                 break;
2062                         case GLOBAL_AREA_ALIGN_BOTTOM:
2063                                 if (screen_rect.ymin > window_rect.ymin) {
2064                                         height += U.pixelsize;
2065                                 }
2066                                 if ((screen_rect.ymin + height) < (window_rect.ymax - 1)) {
2067                                         height += U.pixelsize;
2068                                 }
2069                                 screen_rect.ymin += height;
2070                                 break;
2071                         default:
2072                                 BLI_assert(0);
2073                                 break;
2074                 }
2075         }
2076
2077         BLI_assert(screen_rect.xmin < screen_rect.xmax);
2078         BLI_assert(screen_rect.ymin < screen_rect.ymax);
2079         *r_rect = screen_rect;
2080 }
2081
2082 bool WM_window_is_fullscreen(wmWindow *win)
2083 {
2084         return win->windowstate == GHOST_kWindowStateFullScreen;
2085 }
2086
2087 /**
2088  * Some editor data may need to be synced with scene data (3D View camera and layers).
2089  * This function ensures data is synced for editors in visible workspaces and their visible layouts.
2090  */
2091 void WM_windows_scene_data_sync(const ListBase *win_lb, Scene *scene)
2092 {
2093         for (wmWindow *win = win_lb->first; win; win = win->next) {
2094                 if (WM_window_get_active_scene(win) == scene) {
2095                         ED_workspace_scene_data_sync(win->workspace_hook, scene);
2096                 }
2097         }
2098 }
2099
2100 Scene *WM_windows_scene_get_from_screen(const wmWindowManager *wm, const bScreen *screen)
2101 {
2102         for (wmWindow *win = wm->windows.first; win; win = win->next) {
2103                 if (WM_window_get_active_screen(win) == screen) {
2104                         return WM_window_get_active_scene(win);
2105                 }
2106         }
2107
2108         return NULL;
2109 }
2110
2111 WorkSpace *WM_windows_workspace_get_from_screen(const wmWindowManager *wm, const bScreen *screen)
2112 {
2113         for (wmWindow *win = wm->windows.first; win; win = win->next) {
2114                 if (WM_window_get_active_screen(win) == screen) {
2115                         return WM_window_get_active_workspace(win);
2116                 }
2117         }
2118         return NULL;
2119 }
2120
2121 Scene *WM_window_get_active_scene(const wmWindow *win)
2122 {
2123         return win->scene;
2124 }
2125
2126 /**
2127  * \warning Only call outside of area/region loops
2128  */
2129 void WM_window_set_active_scene(Main *bmain, bContext *C, wmWindow *win, Scene *scene)
2130 {
2131         wmWindowManager *wm = CTX_wm_manager(C);
2132         wmWindow *win_parent = (win->parent) ? win->parent : win;
2133         bool changed = false;
2134
2135         /* Set scene in parent and its child windows. */
2136         if (win_parent->scene != scene) {
2137                 ED_screen_scene_change(C, win_parent, scene);
2138                 changed = true;
2139         }
2140
2141         for (wmWindow *win_child = wm->windows.first; win_child; win_child = win_child->next) {
2142                 if (win_child->parent == win_parent && win_child->scene != scene) {
2143                         ED_screen_scene_change(C, win_child, scene);
2144                         changed = true;
2145                 }
2146         }
2147
2148         if (changed) {
2149                 /* Update depsgraph and renderers for scene change. */
2150                 ViewLayer *view_layer = WM_window_get_active_view_layer(win_parent);
2151                 ED_scene_change_update(bmain, scene, view_layer);
2152
2153                 /* Complete redraw. */
2154                 WM_event_add_notifier(C, NC_WINDOW, NULL);
2155         }
2156 }
2157
2158 ViewLayer *WM_window_get_active_view_layer(const wmWindow *win)
2159 {
2160         Scene *scene = WM_window_get_active_scene(win);
2161         if (scene == NULL) {
2162                 return NULL;
2163         }
2164
2165         ViewLayer *view_layer = BKE_view_layer_find(scene, win->view_layer_name);
2166         if (view_layer) {
2167                 return view_layer;
2168         }
2169
2170         return BKE_view_layer_default_view(scene);
2171 }
2172
2173 void WM_window_set_active_view_layer(wmWindow *win, ViewLayer *view_layer)
2174 {
2175         BLI_assert(BKE_view_layer_find(WM_window_get_active_scene(win), view_layer->name) != NULL);
2176
2177         wmWindowManager *wm = G_MAIN->wm.first;
2178         wmWindow *win_parent = (win->parent) ? win->parent : win;
2179
2180         /* Set  view layer in parent and child windows. */
2181         STRNCPY(win->view_layer_name, view_layer->name);
2182
2183         for (wmWindow *win_child = wm->windows.first; win_child; win_child = win_child->next) {
2184                 if (win_child->parent == win_parent) {
2185                         STRNCPY(win_child->view_layer_name, view_layer->name);
2186                 }
2187         }
2188 }
2189
2190 void WM_window_ensure_active_view_layer(wmWindow *win)
2191 {
2192         /* Update layer name is correct after scene changes, load without UI, etc. */
2193         Scene *scene = WM_window_get_active_scene(win);
2194
2195         if (scene && BKE_view_layer_find(scene, win->view_layer_name) == NULL) {
2196                 ViewLayer *view_layer = BKE_view_layer_default_view(scene);
2197                 STRNCPY(win->view_layer_name, view_layer->name);
2198         }
2199 }
2200
2201 WorkSpace *WM_window_get_active_workspace(const wmWindow *win)
2202 {
2203         return BKE_workspace_active_get(win->workspace_hook);
2204 }
2205
2206 void WM_window_set_active_workspace(bContext *C, wmWindow *win, WorkSpace *workspace)
2207 {
2208         wmWindowManager *wm = CTX_wm_manager(C);
2209         wmWindow *win_parent = (win->parent) ? win->parent : win;
2210
2211         ED_workspace_change(workspace, C, wm, win);
2212
2213         for (wmWindow *win_child = wm->windows.first; win_child; win_child = win_child->next) {
2214                 if (win_child->parent == win_parent) {
2215                         ED_workspace_change(workspace, C, wm, win_child);
2216                 }
2217         }
2218 }
2219
2220 WorkSpaceLayout *WM_window_get_active_layout(const wmWindow *win)
2221 {
2222         const WorkSpace *workspace = WM_window_get_active_workspace(win);
2223         return (LIKELY(workspace != NULL) ? BKE_workspace_active_layout_get(win->workspace_hook) : NULL);
2224 }
2225 void WM_window_set_active_layout(wmWindow *win, WorkSpace *workspace, WorkSpaceLayout *layout)
2226 {
2227         BKE_workspace_hook_layout_for_workspace_set(win->workspace_hook, workspace, layout);
2228 }
2229
2230 /**
2231  * Get the active screen of the active workspace in \a win.
2232  */
2233 bScreen *WM_window_get_active_screen(const wmWindow *win)
2234 {
2235         const WorkSpace *workspace = WM_window_get_active_workspace(win);
2236         /* May be NULL in rare cases like closing Blender */
2237         return (LIKELY(workspace != NULL) ? BKE_workspace_active_screen_get(win->workspace_hook) : NULL);
2238 }
2239 void WM_window_set_active_screen(wmWindow *win, WorkSpace *workspace, bScreen *screen)
2240 {
2241         BKE_workspace_active_screen_set(win->workspace_hook, workspace, screen);
2242 }
2243
2244 bool WM_window_is_temp_screen(const wmWindow *win)
2245 {
2246         const bScreen *screen = WM_window_get_active_screen(win);
2247         return (screen && screen->temp != 0);
2248 }
2249
2250
2251 #ifdef WITH_INPUT_IME
2252 /* note: keep in mind wm_window_IME_begin is also used to reposition the IME window */
2253 void wm_window_IME_begin(wmWindow *win, int x, int y, int w, int h, bool complete)
2254 {
2255         BLI_assert(win);
2256
2257         GHOST_BeginIME(win->ghostwin, x, win->sizey - y, w, h, complete);
2258 }
2259
2260 void wm_window_IME_end(wmWindow *win)
2261 {
2262         BLI_assert(win && win->ime_data);
2263
2264         GHOST_EndIME(win->ghostwin);
2265         win->ime_data = NULL;
2266 }
2267 #endif  /* WITH_INPUT_IME */
2268
2269 /* ****** direct opengl context management ****** */
2270
2271 void *WM_opengl_context_create(void)
2272 {
2273         /* On Windows there is a problem creating contexts that share lists
2274          * from one context that is current in another thread.
2275          * So we should call this function only on the main thread.
2276          */
2277         BLI_assert(BLI_thread_is_main());
2278         BLI_assert(GPU_framebuffer_current_get() == 0);
2279         return GHOST_CreateOpenGLContext(g_system);
2280 }
2281
2282 void WM_opengl_context_dispose(void *context)
2283 {
2284         BLI_assert(GPU_framebuffer_current_get() == 0);
2285         GHOST_DisposeOpenGLContext(g_system, (GHOST_ContextHandle)context);
2286 }
2287
2288 void WM_opengl_context_activate(void *context)
2289 {
2290         BLI_assert(GPU_framebuffer_current_get() == 0);
2291         GHOST_ActivateOpenGLContext((GHOST_ContextHandle)context);
2292 }
2293
2294 void WM_opengl_context_release(void *context)
2295 {
2296         BLI_assert(GPU_framebuffer_current_get() == 0);
2297         GHOST_ReleaseOpenGLContext((GHOST_ContextHandle)context);
2298 }