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