de169881bc4274b22be5130ce1e6b2d6eb21b20a
[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
42 #include "MEM_guardedalloc.h"
43
44 #include "GHOST_C-api.h"
45
46 #include "BLI_math.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_utildefines.h"
49
50 #include "BLT_translation.h"
51
52 #include "BKE_blender.h"
53 #include "BKE_context.h"
54 #include "BKE_library.h"
55 #include "BKE_global.h"
56 #include "BKE_main.h"
57
58
59 #include "RNA_access.h"
60
61 #include "WM_api.h"
62 #include "WM_types.h"
63 #include "wm.h"
64 #include "wm_draw.h"
65 #include "wm_window.h"
66 #include "wm_subwindow.h"
67 #include "wm_event_system.h"
68
69 #include "ED_screen.h"
70 #include "ED_fileselect.h"
71
72 #include "UI_interface.h"
73
74 #include "PIL_time.h"
75
76 #include "GPU_draw.h"
77 #include "GPU_extensions.h"
78 #include "GPU_init_exit.h"
79 #include "GPU_glew.h"
80 #include "BLF_api.h"
81
82 /* for assert */
83 #ifndef NDEBUG
84 #  include "BLI_threads.h"
85 #endif
86
87 /* the global to talk to ghost */
88 static GHOST_SystemHandle g_system = NULL;
89
90 typedef enum WinOverrideFlag {
91         WIN_OVERRIDE_GEOM     = (1 << 0),
92         WIN_OVERRIDE_WINSTATE = (1 << 1)
93 } WinOverrideFlag;
94
95 /* set by commandline */
96 static struct WMInitStruct {
97         /* window geometry */
98         int size_x, size_y;
99         int start_x, start_y;
100
101         int windowstate;
102         WinOverrideFlag override_flag;
103         
104         bool native_pixels;
105 } wm_init_state = {0, 0, 0, 0, GHOST_kWindowStateNormal, 0, true};
106
107 /* ******** win open & close ************ */
108
109 /* XXX this one should correctly check for apple top header...
110  * done for Cocoa : returns window contents (and not frame) max size*/
111 void wm_get_screensize(int *r_width, int *r_height)
112 {
113         unsigned int uiwidth;
114         unsigned int uiheight;
115         
116         GHOST_GetMainDisplayDimensions(g_system, &uiwidth, &uiheight);
117         *r_width = uiwidth;
118         *r_height = uiheight;
119 }
120
121 /* size of all screens (desktop), useful since the mouse is bound by this */
122 void wm_get_desktopsize(int *r_width, int *r_height)
123 {
124         unsigned int uiwidth;
125         unsigned int uiheight;
126
127         GHOST_GetAllDisplayDimensions(g_system, &uiwidth, &uiheight);
128         *r_width = uiwidth;
129         *r_height = uiheight;
130 }
131
132 /* keeps offset and size within monitor bounds */
133 /* XXX solve dual screen... */
134 static void wm_window_check_position(rcti *rect)
135 {
136         int width, height, d;
137         
138         wm_get_screensize(&width, &height);
139         
140         if (rect->xmin < 0) {
141                 rect->xmax -= rect->xmin;
142                 rect->xmin  = 0;
143         }
144         if (rect->ymin < 0) {
145                 rect->ymax -= rect->ymin;
146                 rect->ymin  = 0;
147         }
148         if (rect->xmax > width) {
149                 d = rect->xmax - width;
150                 rect->xmax -= d;
151                 rect->xmin -= d;
152         }
153         if (rect->ymax > height) {
154                 d = rect->ymax - height;
155                 rect->ymax -= d;
156                 rect->ymin -= d;
157         }
158         
159         if (rect->xmin < 0) rect->xmin = 0;
160         if (rect->ymin < 0) rect->ymin = 0;
161 }
162
163
164 static void wm_ghostwindow_destroy(wmWindow *win) 
165 {
166         if (win->ghostwin) {
167                 GHOST_DisposeWindow(g_system, win->ghostwin);
168                 win->ghostwin = NULL;
169                 win->multisamples = 0;
170         }
171 }
172
173 /* including window itself, C can be NULL. 
174  * ED_screen_exit should have been called */
175 void wm_window_free(bContext *C, wmWindowManager *wm, wmWindow *win)
176 {
177         wmTimer *wt, *wtnext;
178         
179         /* update context */
180         if (C) {
181                 WM_event_remove_handlers(C, &win->handlers);
182                 WM_event_remove_handlers(C, &win->modalhandlers);
183
184                 if (CTX_wm_window(C) == win)
185                         CTX_wm_window_set(C, NULL);
186         }
187
188         /* always set drawable and active to NULL,
189          * prevents non-drawable state of main windows (bugs #22967 and #25071, possibly #22477 too) */
190         wm->windrawable = NULL;
191         wm->winactive = NULL;
192
193         /* end running jobs, a job end also removes its timer */
194         for (wt = wm->timers.first; wt; wt = wtnext) {
195                 wtnext = wt->next;
196                 if (wt->win == win && wt->event_type == TIMERJOBS)
197                         wm_jobs_timer_ended(wm, wt);
198         }
199         
200         /* timer removing, need to call this api function */
201         for (wt = wm->timers.first; wt; wt = wtnext) {
202                 wtnext = wt->next;
203                 if (wt->win == win)
204                         WM_event_remove_timer(wm, win, wt);
205         }
206
207         if (win->eventstate) MEM_freeN(win->eventstate);
208         
209         wm_event_free_all(win);
210         wm_subwindows_free(win);
211
212         wm_draw_data_free(win);
213
214         wm_ghostwindow_destroy(win);
215
216         MEM_freeN(win->stereo3d_format);
217
218         MEM_freeN(win);
219 }
220
221 static int find_free_winid(wmWindowManager *wm)
222 {
223         wmWindow *win;
224         int id = 1;
225         
226         for (win = wm->windows.first; win; win = win->next)
227                 if (id <= win->winid)
228                         id = win->winid + 1;
229         
230         return id;
231 }
232
233 /* don't change context itself */
234 wmWindow *wm_window_new(bContext *C)
235 {
236         wmWindowManager *wm = CTX_wm_manager(C);
237         wmWindow *win = MEM_callocN(sizeof(wmWindow), "window");
238         
239         BLI_addtail(&wm->windows, win);
240         win->winid = find_free_winid(wm);
241
242         win->stereo3d_format = MEM_callocN(sizeof(Stereo3dFormat), "Stereo 3D Format (window)");
243
244         return win;
245 }
246
247
248 /* part of wm_window.c api */
249 wmWindow *wm_window_copy(bContext *C, wmWindow *win_src)
250 {
251         wmWindow *win_dst = wm_window_new(C);
252         
253         win_dst->posx = win_src->posx + 10;
254         win_dst->posy = win_src->posy;
255         win_dst->sizex = win_src->sizex;
256         win_dst->sizey = win_src->sizey;
257         
258         /* duplicate assigns to window */
259         win_dst->screen = ED_screen_duplicate(win_dst, win_src->screen);
260         BLI_strncpy(win_dst->screenname, win_dst->screen->id.name + 2, sizeof(win_dst->screenname));
261         win_dst->screen->winid = win_dst->winid;
262
263         win_dst->screen->do_refresh = true;
264         win_dst->screen->do_draw = true;
265
266         win_dst->drawmethod = U.wmdrawmethod;
267
268         BLI_listbase_clear(&win_dst->drawdata);
269
270         *win_dst->stereo3d_format = *win_src->stereo3d_format;
271
272         return win_dst;
273 }
274
275 /**
276  * A higher level version of copy that tests the new window can be added.
277  * (called from the operator directly)
278  */
279 wmWindow *wm_window_copy_test(bContext *C, wmWindow *win_src)
280 {
281         wmWindowManager *wm = CTX_wm_manager(C);
282         wmWindow *win_dst;
283
284         win_dst = wm_window_copy(C, win_src);
285
286         WM_check(C);
287
288         if (win_dst->ghostwin) {
289                 WM_event_add_notifier(C, NC_WINDOW | NA_ADDED, NULL);
290                 return win_dst;
291         }
292         else {
293                 wm_window_close(C, wm, win_dst);
294                 return NULL;
295         }
296 }
297
298 /* this is event from ghost, or exit-blender op */
299 void wm_window_close(bContext *C, wmWindowManager *wm, wmWindow *win)
300 {
301         wmWindow *tmpwin;
302         bool do_exit = false;
303         
304         /* first check if we have to quit (there are non-temp remaining windows) */
305         for (tmpwin = wm->windows.first; tmpwin; tmpwin = tmpwin->next) {
306                 if (tmpwin == win)
307                         continue;
308                 if (tmpwin->screen->temp == 0)
309                         break;
310         }
311
312         if (tmpwin == NULL)
313                 do_exit = 1;
314         
315         if ((U.uiflag & USER_QUIT_PROMPT) && !wm->file_saved && !G.background) {
316                 if (do_exit) {
317                         if (!GHOST_confirmQuit(win->ghostwin))
318                                 return;
319                 }
320         }
321
322         /* let WM_exit do all freeing, for correct quit.blend save */
323         if (do_exit) {
324                 WM_exit(C);
325         }
326         else {
327                 bScreen *screen = win->screen;
328                 
329                 BLI_remlink(&wm->windows, win);
330                 
331                 wm_draw_window_clear(win);
332                 
333                 CTX_wm_window_set(C, win);  /* needed by handlers */
334                 WM_event_remove_handlers(C, &win->handlers);
335                 WM_event_remove_handlers(C, &win->modalhandlers);
336
337                 /* for regular use this will _never_ be NULL,
338                  * however we may be freeing an improperly initialized window. */
339                 if (win->screen) {
340                         ED_screen_exit(C, win, win->screen);
341                 }
342                 
343                 wm_window_free(C, wm, win);
344         
345                 /* if temp screen, delete it after window free (it stops jobs that can access it) */
346                 if (screen && screen->temp) {
347                         Main *bmain = CTX_data_main(C);
348                         BKE_libblock_free(bmain, screen);
349                 }
350         }               
351 }
352
353 void wm_window_title(wmWindowManager *wm, wmWindow *win)
354 {
355         if (win->screen && win->screen->temp) {
356                 /* nothing to do for 'temp' windows,
357                  * because WM_window_open_temp always sets window title  */
358         }
359         else if (win->ghostwin) {
360                 /* this is set to 1 if you don't have startup.blend open */
361                 if (G.save_over && G.main->name[0]) {
362                         char str[sizeof(G.main->name) + 24];
363                         BLI_snprintf(str, sizeof(str), "Blender%s [%s%s]", wm->file_saved ? "" : "*", G.main->name,
364                                      G.main->recovered ? " (Recovered)" : "");
365                         GHOST_SetTitle(win->ghostwin, str);
366                 }
367                 else
368                         GHOST_SetTitle(win->ghostwin, "Blender");
369
370                 /* Informs GHOST of unsaved changes, to set window modified visual indicator (MAC OS X)
371                  * and to give hint of unsaved changes for a user warning mechanism
372                  * in case of OS application terminate request (e.g. OS Shortcut Alt+F4, Cmd+Q, (...), or session end) */
373                 GHOST_SetWindowModifiedState(win->ghostwin, (GHOST_TUns8) !wm->file_saved);
374                 
375         }
376 }
377
378 static void wm_window_set_dpi(wmWindow *win)
379 {
380         int auto_dpi = GHOST_GetDPIHint(win->ghostwin);
381
382         /* Lazily init UI scale size, preserving backwards compatibility by
383          * computing UI scale from ratio of previous DPI and auto DPI */
384         if (U.ui_scale == 0) {
385                 int virtual_pixel = (U.virtual_pixel == VIRTUAL_PIXEL_NATIVE) ? 1 : 2;
386
387                 if (U.dpi == 0) {
388                         U.ui_scale = virtual_pixel;
389                 }
390                 else {
391                         U.ui_scale = (virtual_pixel * U.dpi * 96.0f) / (auto_dpi * 72.0f);
392                 }
393
394                 CLAMP(U.ui_scale, 0.25f, 4.0f);
395         }
396
397         /* Blender's UI drawing assumes DPI 72 as a good default following macOS
398          * while Windows and Linux use DPI 96. GHOST assumes a default 96 so we
399          * remap the DPI to Blender's convention. */
400         int dpi = auto_dpi * U.ui_scale * (72.0 / 96.0f);
401
402         /* Automatically set larger pixel size for high DPI. */
403         int pixelsize = MAX2(1, dpi / 54);
404
405         /* Set user preferences globals for drawing, and for forward compatibility. */
406         U.pixelsize = GHOST_GetNativePixelSize(win->ghostwin) * pixelsize;
407         U.dpi = dpi / pixelsize;
408         U.virtual_pixel = (pixelsize == 1) ? VIRTUAL_PIXEL_NATIVE : VIRTUAL_PIXEL_DOUBLE;
409
410         BKE_blender_userdef_refresh();
411 }
412
413 /* belongs to below */
414 static void wm_window_ghostwindow_add(wmWindowManager *wm, const char *title, wmWindow *win)
415 {
416         GHOST_WindowHandle ghostwin;
417         GHOST_GLSettings glSettings = {0};
418         static int multisamples = -1;
419         int scr_w, scr_h, posy;
420         
421         /* force setting multisamples only once, it requires restart - and you cannot 
422          * mix it, either all windows have it, or none (tested in OSX opengl) */
423         if (multisamples == -1)
424                 multisamples = U.ogl_multisamples;
425
426         glSettings.numOfAASamples = multisamples;
427
428         /* a new window is created when pageflip mode is required for a window */
429         if (win->stereo3d_format->display_mode == S3D_DISPLAY_PAGEFLIP)
430                 glSettings.flags |= GHOST_glStereoVisual;
431
432         if (G.debug & G_DEBUG_GPU) {
433                 glSettings.flags |= GHOST_glDebugContext;
434         }
435
436         wm_get_screensize(&scr_w, &scr_h);
437         posy = (scr_h - win->posy - win->sizey);
438         
439         ghostwin = GHOST_CreateWindow(g_system, title,
440                                       win->posx, posy, win->sizex, win->sizey,
441 #ifdef __APPLE__
442                                       /* we agreed to not set any fullscreen or iconized state on startup */
443                                       GHOST_kWindowStateNormal,
444 #else
445                                       (GHOST_TWindowState)win->windowstate,
446 #endif
447                                       GHOST_kDrawingContextTypeOpenGL,
448                                       glSettings);
449         
450         if (ghostwin) {
451                 GHOST_RectangleHandle bounds;
452                 
453                 /* the new window has already been made drawable upon creation */
454                 wm->windrawable = win;
455
456                 /* needed so we can detect the graphics card below */
457                 GPU_init();
458                 
459                 win->ghostwin = ghostwin;
460                 GHOST_SetWindowUserData(ghostwin, win); /* pointer back */
461                 
462                 if (win->eventstate == NULL)
463                         win->eventstate = MEM_callocN(sizeof(wmEvent), "window event state");
464
465                 /* store multisamples window was created with, in case user prefs change */
466                 win->multisamples = multisamples;
467                 
468                 /* store actual window size in blender window */
469                 bounds = GHOST_GetClientBounds(win->ghostwin);
470                 win->sizex = GHOST_GetWidthRectangle(bounds);
471                 win->sizey = GHOST_GetHeightRectangle(bounds);
472                 GHOST_DisposeRectangle(bounds);
473                 
474 #ifndef __APPLE__
475                 /* set the state here, so minimized state comes up correct on windows */
476                 GHOST_SetWindowState(ghostwin, (GHOST_TWindowState)win->windowstate);
477 #endif
478                 /* until screens get drawn, make it nice gray */
479                 glClearColor(0.55, 0.55, 0.55, 0.0);
480                 /* Crash on OSS ATI: bugs.launchpad.net/ubuntu/+source/mesa/+bug/656100 */
481                 if (!GPU_type_matches(GPU_DEVICE_ATI, GPU_OS_UNIX, GPU_DRIVER_OPENSOURCE)) {
482                         glClear(GL_COLOR_BUFFER_BIT);
483                 }
484                 
485                 /* needed here, because it's used before it reads userdef */
486                 wm_window_set_dpi(win);
487                 
488                 wm_window_swap_buffers(win);
489                 
490                 //GHOST_SetWindowState(ghostwin, GHOST_kWindowStateModified);
491                 
492                 /* standard state vars for window */
493                 glEnable(GL_SCISSOR_TEST);
494                 GPU_state_init();
495         }
496 }
497
498 /**
499  * Initialize #wmWindows without ghostwin, open these and clear.
500  *
501  * window size is read from window, if 0 it uses prefsize
502  * called in #WM_check, also inits stuff after file read.
503  *
504  * \warning
505  * After running, 'win->ghostwin' can be NULL in rare cases
506  * (where OpenGL driver fails to create a context for eg).
507  * We could remove them with #wm_window_ghostwindows_remove_invalid
508  * but better not since caller may continue to use.
509  * Instead, caller needs to handle the error case and cleanup.
510  */
511 void wm_window_ghostwindows_ensure(wmWindowManager *wm)
512 {
513         wmKeyMap *keymap;
514         wmWindow *win;
515         
516         BLI_assert(G.background == false);
517
518         /* no commandline prefsize? then we set this.
519          * Note that these values will be used only
520          * when there is no startup.blend yet.
521          */
522         if (wm_init_state.size_x == 0) {
523                 wm_get_screensize(&wm_init_state.size_x, &wm_init_state.size_y);
524                 
525                 /* note!, this isnt quite correct, active screen maybe offset 1000s if PX,
526                  * we'd need a wm_get_screensize like function that gives offset,
527                  * in practice the window manager will likely move to the correct monitor */
528                 wm_init_state.start_x = 0;
529                 wm_init_state.start_y = 0;
530
531 #ifdef WITH_X11 /* X11 */
532                 /* X11, start maximized but use default sane size */
533                 wm_init_state.size_x = min_ii(wm_init_state.size_x, WM_WIN_INIT_SIZE_X);
534                 wm_init_state.size_y = min_ii(wm_init_state.size_y, WM_WIN_INIT_SIZE_Y);
535                 /* pad */
536                 wm_init_state.start_x = WM_WIN_INIT_PAD;
537                 wm_init_state.start_y = WM_WIN_INIT_PAD;
538                 wm_init_state.size_x -= WM_WIN_INIT_PAD * 2;
539                 wm_init_state.size_y -= WM_WIN_INIT_PAD * 2;
540 #endif
541         }
542         
543         for (win = wm->windows.first; win; win = win->next) {
544                 if (win->ghostwin == NULL) {
545                         if ((win->sizex == 0) || (wm_init_state.override_flag & WIN_OVERRIDE_GEOM)) {
546                                 win->posx = wm_init_state.start_x;
547                                 win->posy = wm_init_state.start_y;
548                                 win->sizex = wm_init_state.size_x;
549                                 win->sizey = wm_init_state.size_y;
550
551                                 win->windowstate = GHOST_kWindowStateNormal;
552                                 wm_init_state.override_flag &= ~WIN_OVERRIDE_GEOM;
553                         }
554
555                         if (wm_init_state.override_flag & WIN_OVERRIDE_WINSTATE) {
556                                 win->windowstate = wm_init_state.windowstate;
557                                 wm_init_state.override_flag &= ~WIN_OVERRIDE_WINSTATE;
558                         }
559
560                         /* without this, cursor restore may fail, T45456 */
561                         if (win->cursor == 0) {
562                                 win->cursor = CURSOR_STD;
563                         }
564
565                         wm_window_ghostwindow_add(wm, "Blender", win);
566                 }
567                 /* happens after fileread */
568                 if (win->eventstate == NULL)
569                         win->eventstate = MEM_callocN(sizeof(wmEvent), "window event state");
570
571                 /* add keymap handlers (1 handler for all keys in map!) */
572                 keymap = WM_keymap_find(wm->defaultconf, "Window", 0, 0);
573                 WM_event_add_keymap_handler(&win->handlers, keymap);
574                 
575                 keymap = WM_keymap_find(wm->defaultconf, "Screen", 0, 0);
576                 WM_event_add_keymap_handler(&win->handlers, keymap);
577
578                 keymap = WM_keymap_find(wm->defaultconf, "Screen Editing", 0, 0);
579                 WM_event_add_keymap_handler(&win->modalhandlers, keymap);
580                 
581                 /* add drop boxes */
582                 {
583                         ListBase *lb = WM_dropboxmap_find("Window", 0, 0);
584                         WM_event_add_dropbox_handler(&win->handlers, lb);
585                 }
586                 wm_window_title(wm, win);
587         }
588 }
589
590 /**
591  * Call after #wm_window_ghostwindows_ensure or #WM_check
592  * (after loading a new file) in the unlikely event a window couldn't be created.
593  */
594 void wm_window_ghostwindows_remove_invalid(bContext *C, wmWindowManager *wm)
595 {
596         wmWindow *win, *win_next;
597
598         BLI_assert(G.background == false);
599
600         for (win = wm->windows.first; win; win = win_next) {
601                 win_next = win->next;
602                 if (win->ghostwin == NULL) {
603                         wm_window_close(C, wm, win);
604                 }
605         }
606 }
607
608 /**
609  * new window, no screen yet, but we open ghostwindow for it,
610  * also gets the window level handlers
611  * \note area-rip calls this.
612  * \return the window or NULL.
613  */
614 wmWindow *WM_window_open(bContext *C, const rcti *rect)
615 {
616         wmWindow *win_prev = CTX_wm_window(C);
617         wmWindow *win = wm_window_new(C);
618         
619         win->posx = rect->xmin;
620         win->posy = rect->ymin;
621         win->sizex = BLI_rcti_size_x(rect);
622         win->sizey = BLI_rcti_size_y(rect);
623
624         win->drawmethod = U.wmdrawmethod;
625
626         WM_check(C);
627
628         if (win->ghostwin) {
629                 return win;
630         }
631         else {
632                 wm_window_close(C, CTX_wm_manager(C), win);
633                 CTX_wm_window_set(C, win_prev);
634                 return NULL;
635         }
636 }
637
638 /**
639  * Uses `screen->temp` tag to define what to do, currently it limits
640  * to only one "temp" window for render out, preferences, filewindow, etc...
641  *
642  * \param type: WM_WINDOW_RENDER, WM_WINDOW_USERPREFS...
643  * \return the window or NULL.
644  */
645 wmWindow *WM_window_open_temp(bContext *C, int x, int y, int sizex, int sizey, int type)
646 {
647         wmWindow *win_prev = CTX_wm_window(C);
648         wmWindow *win;
649         ScrArea *sa;
650         Scene *scene = CTX_data_scene(C);
651         const char *title;
652
653         /* convert to native OS window coordinates */
654         const float native_pixel_size = GHOST_GetNativePixelSize(win_prev->ghostwin);
655         x /= native_pixel_size;
656         y /= native_pixel_size;
657         sizex /= native_pixel_size;
658         sizey /= native_pixel_size;
659
660         /* calculate postition */
661         rcti rect;
662         rect.xmin = x + win_prev->posx - sizex / 2;
663         rect.ymin = y + win_prev->posy - sizey / 2;
664         rect.xmax = rect.xmin + sizex;
665         rect.ymax = rect.ymin + sizey;
666
667         /* changes rect to fit within desktop */
668         wm_window_check_position(&rect);
669         
670         /* test if we have a temp screen already */
671         for (win = CTX_wm_manager(C)->windows.first; win; win = win->next)
672                 if (win->screen->temp)
673                         break;
674         
675         /* add new window? */
676         if (win == NULL) {
677                 win = wm_window_new(C);
678                 
679                 win->posx = rect.xmin;
680                 win->posy = rect.ymin;
681         }
682
683         win->sizex = BLI_rcti_size_x(&rect);
684         win->sizey = BLI_rcti_size_y(&rect);
685
686         if (win->ghostwin) {
687                 wm_window_set_size(win, win->sizex, win->sizey);
688                 wm_window_raise(win);
689         }
690         
691         if (win->screen == NULL) {
692                 /* add new screen */
693                 win->screen = ED_screen_add(win, scene, "temp");
694         }
695         else {
696                 /* switch scene for rendering */
697                 if (win->screen->scene != scene)
698                         ED_screen_set_scene(C, win->screen, scene);
699         }
700
701         win->screen->temp = 1; 
702         
703         /* make window active, and validate/resize */
704         CTX_wm_window_set(C, win);
705         WM_check(C);
706
707         /* It's possible `win->ghostwin == NULL`.
708          * instead of attempting to cleanup here (in a half finished state),
709          * finish setting up the screen, then free it at the end of the function,
710          * to avoid having to take into account a partially-created window.
711          */
712
713         /* ensure it shows the right spacetype editor */
714         sa = win->screen->areabase.first;
715         CTX_wm_area_set(C, sa);
716         
717         if (type == WM_WINDOW_RENDER) {
718                 ED_area_newspace(C, sa, SPACE_IMAGE, false);
719         }
720         else {
721                 ED_area_newspace(C, sa, SPACE_USERPREF, false);
722         }
723         
724         ED_screen_set(C, win->screen);
725         ED_screen_refresh(CTX_wm_manager(C), win); /* test scale */
726         
727         if (sa->spacetype == SPACE_IMAGE)
728                 title = IFACE_("Blender Render");
729         else if (ELEM(sa->spacetype, SPACE_OUTLINER, SPACE_USERPREF))
730                 title = IFACE_("Blender User Preferences");
731         else if (sa->spacetype == SPACE_FILE)
732                 title = IFACE_("Blender File View");
733         else
734                 title = "Blender";
735
736         if (win->ghostwin) {
737                 GHOST_SetTitle(win->ghostwin, title);
738                 return win;
739         }
740         else {
741                 /* very unlikely! but opening a new window can fail */
742                 wm_window_close(C, CTX_wm_manager(C), win);
743                 CTX_wm_window_set(C, win_prev);
744
745                 return NULL;
746         }
747 }
748
749
750 /* ****************** Operators ****************** */
751
752 int wm_window_close_exec(bContext *C, wmOperator *UNUSED(op))
753 {
754         wmWindowManager *wm = CTX_wm_manager(C);
755         wmWindow *win = CTX_wm_window(C);
756         wm_window_close(C, wm, win);
757         return OPERATOR_FINISHED;
758 }
759
760 /* operator callback */
761 int wm_window_duplicate_exec(bContext *C, wmOperator *UNUSED(op))
762 {
763         wmWindow *win_src = CTX_wm_window(C);
764         bool ok;
765
766         ok = (wm_window_copy_test(C, win_src) != NULL);
767
768         return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
769 }
770
771
772 /* fullscreen operator callback */
773 int wm_window_fullscreen_toggle_exec(bContext *C, wmOperator *UNUSED(op))
774 {
775         wmWindow *window = CTX_wm_window(C);
776         GHOST_TWindowState state;
777
778         if (G.background)
779                 return OPERATOR_CANCELLED;
780
781         state = GHOST_GetWindowState(window->ghostwin);
782         if (state != GHOST_kWindowStateFullScreen)
783                 GHOST_SetWindowState(window->ghostwin, GHOST_kWindowStateFullScreen);
784         else
785                 GHOST_SetWindowState(window->ghostwin, GHOST_kWindowStateNormal);
786
787         return OPERATOR_FINISHED;
788         
789 }
790
791
792 /* ************ events *************** */
793
794 void wm_cursor_position_from_ghost(wmWindow *win, int *x, int *y)
795 {
796         float fac = GHOST_GetNativePixelSize(win->ghostwin);
797         
798         GHOST_ScreenToClient(win->ghostwin, *x, *y, x, y);
799         *x *= fac;
800         
801         *y = (win->sizey - 1) - *y;
802         *y *= fac;
803 }
804
805 void wm_cursor_position_to_ghost(wmWindow *win, int *x, int *y)
806 {
807         float fac = GHOST_GetNativePixelSize(win->ghostwin);
808
809         *x /= fac;
810         *y /= fac;
811         *y = win->sizey - *y - 1;
812
813         GHOST_ClientToScreen(win->ghostwin, *x, *y, x, y);
814 }
815
816 void wm_get_cursor_position(wmWindow *win, int *x, int *y)
817 {
818         GHOST_GetCursorPosition(g_system, x, y);
819         wm_cursor_position_from_ghost(win, x, y);
820 }
821
822 typedef enum {
823         SHIFT    = 's',
824         CONTROL  = 'c',
825         ALT      = 'a',
826         OS       = 'C'
827 } modifierKeyType;
828
829 /* check if specified modifier key type is pressed */
830 static int query_qual(modifierKeyType qual) 
831 {
832         GHOST_TModifierKeyMask left, right;
833         int val = 0;
834         
835         switch (qual) {
836                 case SHIFT:
837                         left = GHOST_kModifierKeyLeftShift;
838                         right = GHOST_kModifierKeyRightShift;
839                         break;
840                 case CONTROL:
841                         left = GHOST_kModifierKeyLeftControl;
842                         right = GHOST_kModifierKeyRightControl;
843                         break;
844                 case OS:
845                         left = right = GHOST_kModifierKeyOS;
846                         break;
847                 case ALT:
848                 default:
849                         left = GHOST_kModifierKeyLeftAlt;
850                         right = GHOST_kModifierKeyRightAlt;
851                         break;
852         }
853         
854         GHOST_GetModifierKeyState(g_system, left, &val);
855         if (!val)
856                 GHOST_GetModifierKeyState(g_system, right, &val);
857         
858         return val;
859 }
860
861 void wm_window_make_drawable(wmWindowManager *wm, wmWindow *win) 
862 {
863         if (win != wm->windrawable && win->ghostwin) {
864 //              win->lmbut = 0; /* keeps hanging when mousepressed while other window opened */
865                 
866                 wm->windrawable = win;
867                 if (G.debug & G_DEBUG_EVENTS) {
868                         printf("%s: set drawable %d\n", __func__, win->winid);
869                 }
870                 GHOST_ActivateWindowDrawingContext(win->ghostwin);
871                 
872                 /* this can change per window */
873                 wm_window_set_dpi(win);
874         }
875 }
876
877 /* called by ghost, here we handle events for windows themselves or send to event system */
878 /* mouse coordinate converversion happens here */
879 static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr)
880 {
881         bContext *C = C_void_ptr;
882         wmWindowManager *wm = CTX_wm_manager(C);
883         GHOST_TEventType type = GHOST_GetEventType(evt);
884         int time = GHOST_GetEventTime(evt);
885         
886         if (type == GHOST_kEventQuit) {
887                 WM_exit(C);
888         }
889         else {
890                 GHOST_WindowHandle ghostwin = GHOST_GetEventWindow(evt);
891                 GHOST_TEventDataPtr data = GHOST_GetEventData(evt);
892                 wmWindow *win;
893                 
894                 /* Ghost now can call this function for life resizes, but it should return if WM didn't initialize yet.
895                  * Can happen on file read (especially full size window)  */
896                 if ((wm->initialized & WM_INIT_WINDOW) == 0) {
897                         return 1;
898                 }
899                 if (!ghostwin) {
900                         /* XXX - should be checked, why are we getting an event here, and */
901                         /* what is it? */
902                         puts("<!> event has no window");
903                         return 1;
904                 }
905                 else if (!GHOST_ValidWindow(g_system, ghostwin)) {
906                         /* XXX - should be checked, why are we getting an event here, and */
907                         /* what is it? */
908                         puts("<!> event has invalid window");
909                         return 1;
910                 }
911                 else {
912                         win = GHOST_GetWindowUserData(ghostwin);
913                 }
914                 
915                 switch (type) {
916                         case GHOST_kEventWindowDeactivate:
917                                 wm_event_add_ghostevent(wm, win, type, time, data);
918                                 win->active = 0; /* XXX */
919                                 
920                                 /* clear modifiers for inactive windows */
921                                 win->eventstate->alt = 0;
922                                 win->eventstate->ctrl = 0;
923                                 win->eventstate->shift = 0;
924                                 win->eventstate->oskey = 0;
925                                 win->eventstate->keymodifier = 0;
926
927                                 break;
928                         case GHOST_kEventWindowActivate: 
929                         {
930                                 GHOST_TEventKeyData kdata;
931                                 wmEvent event;
932                                 int wx, wy;
933                                 const int keymodifier = ((query_qual(SHIFT)     ? KM_SHIFT : 0) |
934                                                          (query_qual(CONTROL)   ? KM_CTRL  : 0) |
935                                                          (query_qual(ALT)       ? KM_ALT   : 0) |
936                                                          (query_qual(OS)        ? KM_OSKEY : 0));
937
938                                 /* Win23/GHOST modifier bug, see T40317 */
939 #ifndef WIN32
940 //#  define USE_WIN_ACTIVATE
941 #endif
942
943                                 wm->winactive = win; /* no context change! c->wm->windrawable is drawable, or for area queues */
944                                 
945                                 win->active = 1;
946 //                              window_handle(win, INPUTCHANGE, win->active);
947                                 
948                                 /* bad ghost support for modifier keys... so on activate we set the modifiers again */
949
950                                 /* TODO: This is not correct since a modifier may be held when a window is activated...
951                                  * better solve this at ghost level. attempted fix r54450 but it caused bug [#34255]
952                                  *
953                                  * For now don't send GHOST_kEventKeyDown events, just set the 'eventstate'.
954                                  */
955                                 kdata.ascii = '\0';
956                                 kdata.utf8_buf[0] = '\0';
957
958                                 if (win->eventstate->shift) {
959                                         if ((keymodifier & KM_SHIFT) == 0) {
960                                                 kdata.key = GHOST_kKeyLeftShift;
961                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
962                                         }
963                                 }
964 #ifdef USE_WIN_ACTIVATE
965                                 else {
966                                         if (keymodifier & KM_SHIFT) {
967                                                 win->eventstate->shift = KM_MOD_FIRST;
968                                         }
969                                 }
970 #endif
971                                 if (win->eventstate->ctrl) {
972                                         if ((keymodifier & KM_CTRL) == 0) {
973                                                 kdata.key = GHOST_kKeyLeftControl;
974                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
975                                         }
976                                 }
977 #ifdef USE_WIN_ACTIVATE
978                                 else {
979                                         if (keymodifier & KM_CTRL) {
980                                                 win->eventstate->ctrl = KM_MOD_FIRST;
981                                         }
982                                 }
983 #endif
984                                 if (win->eventstate->alt) {
985                                         if ((keymodifier & KM_ALT) == 0) {
986                                                 kdata.key = GHOST_kKeyLeftAlt;
987                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
988                                         }
989                                 }
990 #ifdef USE_WIN_ACTIVATE
991                                 else {
992                                         if (keymodifier & KM_ALT) {
993                                                 win->eventstate->alt = KM_MOD_FIRST;
994                                         }
995                                 }
996 #endif
997                                 if (win->eventstate->oskey) {
998                                         if ((keymodifier & KM_OSKEY) == 0) {
999                                                 kdata.key = GHOST_kKeyOS;
1000                                                 wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
1001                                         }
1002                                 }
1003 #ifdef USE_WIN_ACTIVATE
1004                                 else {
1005                                         if (keymodifier & KM_OSKEY) {
1006                                                 win->eventstate->oskey = KM_MOD_FIRST;
1007                                         }
1008                                 }
1009 #endif
1010
1011 #undef USE_WIN_ACTIVATE
1012
1013
1014                                 /* keymodifier zero, it hangs on hotkeys that open windows otherwise */
1015                                 win->eventstate->keymodifier = 0;
1016                                 
1017                                 /* entering window, update mouse pos. but no event */
1018                                 wm_get_cursor_position(win,  &wx, &wy);
1019
1020                                 win->eventstate->x = wx;
1021                                 win->eventstate->y = wy;
1022                                 
1023                                 win->addmousemove = 1;   /* enables highlighted buttons */
1024                                 
1025                                 wm_window_make_drawable(wm, win);
1026
1027                                 /* window might be focused by mouse click in configuration of window manager
1028                                  * when focus is not following mouse
1029                                  * click could have been done on a button and depending on window manager settings
1030                                  * click would be passed to blender or not, but in any case button under cursor
1031                                  * should be activated, so at max next click on button without moving mouse
1032                                  * would trigger it's handle function
1033                                  * currently it seems to be common practice to generate new event for, but probably
1034                                  * we'll need utility function for this? (sergey)
1035                                  */
1036                                 wm_event_init_from_window(win, &event);
1037                                 event.type = MOUSEMOVE;
1038                                 event.prevx = event.x;
1039                                 event.prevy = event.y;
1040
1041                                 wm_event_add(win, &event);
1042
1043                                 break;
1044                         }
1045                         case GHOST_kEventWindowClose:
1046                         {
1047                                 wm_window_close(C, wm, win);
1048                                 break;
1049                         }
1050                         case GHOST_kEventWindowUpdate:
1051                         {
1052                                 if (G.debug & G_DEBUG_EVENTS) {
1053                                         printf("%s: ghost redraw %d\n", __func__, win->winid);
1054                                 }
1055                                 
1056                                 wm_window_make_drawable(wm, win);
1057                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
1058
1059                                 break;
1060                         }
1061                         case GHOST_kEventWindowSize:
1062                         case GHOST_kEventWindowMove:
1063                         {
1064                                 GHOST_TWindowState state;
1065                                 state = GHOST_GetWindowState(win->ghostwin);
1066                                 win->windowstate = state;
1067
1068                                 /* stop screencast if resize */
1069                                 if (type == GHOST_kEventWindowSize) {
1070                                         WM_jobs_stop(wm, win->screen, NULL);
1071                                 }
1072
1073                                 wm_window_set_dpi(win);
1074                                 
1075                                 /* win32: gives undefined window size when minimized */
1076                                 if (state != GHOST_kWindowStateMinimized) {
1077                                         GHOST_RectangleHandle client_rect;
1078                                         int l, t, r, b, scr_w, scr_h;
1079                                         int sizex, sizey, posx, posy;
1080                                         
1081                                         client_rect = GHOST_GetClientBounds(win->ghostwin);
1082                                         GHOST_GetRectangle(client_rect, &l, &t, &r, &b);
1083                                         
1084                                         GHOST_DisposeRectangle(client_rect);
1085                                         
1086                                         wm_get_desktopsize(&scr_w, &scr_h);
1087                                         sizex = r - l;
1088                                         sizey = b - t;
1089                                         posx = l;
1090                                         posy = scr_h - t - win->sizey;
1091
1092                                         /*
1093                                          * Ghost sometimes send size or move events when the window hasn't changed.
1094                                          * One case of this is using compiz on linux. To alleviate the problem
1095                                          * we ignore all such event here.
1096                                          * 
1097                                          * It might be good to eventually do that at Ghost level, but that is for 
1098                                          * another time.
1099                                          */
1100                                         if (win->sizex != sizex ||
1101                                             win->sizey != sizey ||
1102                                             win->posx != posx ||
1103                                             win->posy != posy)
1104                                         {
1105                                                 win->sizex = sizex;
1106                                                 win->sizey = sizey;
1107                                                 win->posx = posx;
1108                                                 win->posy = posy;
1109
1110                                                 /* debug prints */
1111                                                 if (G.debug & G_DEBUG_EVENTS) {
1112                                                         const char *state_str;
1113                                                         state = GHOST_GetWindowState(win->ghostwin);
1114
1115                                                         if (state == GHOST_kWindowStateNormal) {
1116                                                                 state_str = "normal";
1117                                                         }
1118                                                         else if (state == GHOST_kWindowStateMinimized) {
1119                                                                 state_str = "minimized";
1120                                                         }
1121                                                         else if (state == GHOST_kWindowStateMaximized) {
1122                                                                 state_str = "maximized";
1123                                                         }
1124                                                         else if (state == GHOST_kWindowStateFullScreen) {
1125                                                                 state_str = "fullscreen";
1126                                                         }
1127                                                         else {
1128                                                                 state_str = "<unknown>";
1129                                                         }
1130
1131                                                         printf("%s: window %d state = %s\n", __func__, win->winid, state_str);
1132
1133                                                         if (type != GHOST_kEventWindowSize) {
1134                                                                 printf("win move event pos %d %d size %d %d\n",
1135                                                                        win->posx, win->posy, win->sizex, win->sizey);
1136                                                         }
1137                                                 }
1138                                         
1139                                                 wm_window_make_drawable(wm, win);
1140                                                 wm_draw_window_clear(win);
1141                                                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1142                                                 WM_event_add_notifier(C, NC_WINDOW | NA_EDITED, NULL);
1143                                                 
1144 #if defined(__APPLE__) || defined(WIN32)
1145                                                 /* OSX and Win32 don't return to the mainloop while resize */
1146                                                 wm_event_do_notifiers(C);
1147                                                 wm_draw_update(C);
1148
1149                                                 /* Warning! code above nulls 'C->wm.window', causing BGE to quit, see: T45699.
1150                                                  * Further, its easier to match behavior across platforms, so restore the window. */
1151                                                 CTX_wm_window_set(C, win);
1152 #endif
1153                                         }
1154                                 }
1155                                 break;
1156                         }
1157
1158                         case GHOST_kEventWindowDPIHintChanged:
1159                         {
1160                                 wm_window_set_dpi(win);
1161                                 /* font's are stored at each DPI level, without this we can easy load 100's of fonts */
1162                                 BLF_cache_clear();
1163
1164                                 BKE_blender_userdef_refresh();
1165                                 WM_main_add_notifier(NC_WINDOW, NULL);      /* full redraw */
1166                                 WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL);    /* refresh region sizes */
1167                                 break;
1168                         }
1169
1170                         case GHOST_kEventOpenMainFile:
1171                         {
1172                                 PointerRNA props_ptr;
1173                                 wmWindow *oldWindow;
1174                                 const char *path = GHOST_GetEventData(evt);
1175                                 
1176                                 if (path) {
1177                                         wmOperatorType *ot = WM_operatortype_find("WM_OT_open_mainfile", false);
1178                                         /* operator needs a valid window in context, ensures
1179                                          * it is correctly set */
1180                                         oldWindow = CTX_wm_window(C);
1181                                         CTX_wm_window_set(C, win);
1182                                         
1183                                         WM_operator_properties_create_ptr(&props_ptr, ot);
1184                                         RNA_string_set(&props_ptr, "filepath", path);
1185                                         WM_operator_name_call_ptr(C, ot, WM_OP_EXEC_DEFAULT, &props_ptr);
1186                                         WM_operator_properties_free(&props_ptr);
1187                                         
1188                                         CTX_wm_window_set(C, oldWindow);
1189                                 }
1190                                 break;
1191                         }
1192                         case GHOST_kEventDraggingDropDone:
1193                         {
1194                                 wmEvent event;
1195                                 GHOST_TEventDragnDropData *ddd = GHOST_GetEventData(evt);
1196                                 int wx, wy;
1197                                 
1198                                 /* entering window, update mouse pos */
1199                                 wm_get_cursor_position(win, &wx, &wy);
1200                                 win->eventstate->x = wx;
1201                                 win->eventstate->y = wy;
1202                                 
1203                                 wm_event_init_from_window(win, &event);  /* copy last state, like mouse coords */
1204                                 
1205                                 /* activate region */
1206                                 event.type = MOUSEMOVE;
1207                                 event.prevx = event.x;
1208                                 event.prevy = event.y;
1209                                 
1210                                 wm->winactive = win; /* no context change! c->wm->windrawable is drawable, or for area queues */
1211                                 win->active = 1;
1212                                 
1213                                 wm_event_add(win, &event);
1214                                 
1215                                 
1216                                 /* make blender drop event with custom data pointing to wm drags */
1217                                 event.type = EVT_DROP;
1218                                 event.val = KM_RELEASE;
1219                                 event.custom = EVT_DATA_DRAGDROP;
1220                                 event.customdata = &wm->drags;
1221                                 event.customdatafree = 1;
1222                                 
1223                                 wm_event_add(win, &event);
1224                                 
1225                                 /* printf("Drop detected\n"); */
1226                                 
1227                                 /* add drag data to wm for paths: */
1228                                 
1229                                 if (ddd->dataType == GHOST_kDragnDropTypeFilenames) {
1230                                         GHOST_TStringArray *stra = ddd->data;
1231                                         int a, icon;
1232                                         
1233                                         for (a = 0; a < stra->count; a++) {
1234                                                 printf("drop file %s\n", stra->strings[a]);
1235                                                 /* try to get icon type from extension */
1236                                                 icon = ED_file_extension_icon((char *)stra->strings[a]);
1237                                                 
1238                                                 WM_event_start_drag(C, icon, WM_DRAG_PATH, stra->strings[a], 0.0, WM_DRAG_NOP);
1239                                                 /* void poin should point to string, it makes a copy */
1240                                                 break; /* only one drop element supported now */
1241                                         }
1242                                 }
1243                                 
1244                                 break;
1245                         }
1246                         case GHOST_kEventNativeResolutionChange:
1247                         {
1248                                 // only update if the actual pixel size changes
1249                                 float prev_pixelsize = U.pixelsize;
1250                                 wm_window_set_dpi(win);
1251
1252                                 if (U.pixelsize != prev_pixelsize) {
1253                                         // close all popups since they are positioned with the pixel
1254                                         // size baked in and it's difficult to correct them
1255                                         wmWindow *oldWindow = CTX_wm_window(C);
1256                                         CTX_wm_window_set(C, win);
1257                                         UI_popup_handlers_remove_all(C, &win->modalhandlers);
1258                                         CTX_wm_window_set(C, oldWindow);
1259
1260                                         wm_window_make_drawable(wm, win);
1261                                         wm_draw_window_clear(win);
1262
1263                                         WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
1264                                         WM_event_add_notifier(C, NC_WINDOW | NA_EDITED, NULL);
1265                                 }
1266
1267                                 break;
1268                         }
1269                         case GHOST_kEventTrackpad:
1270                         {
1271                                 GHOST_TEventTrackpadData *pd = data;
1272                                 
1273                                 wm_cursor_position_from_ghost(win, &pd->x, &pd->y);
1274                                 wm_event_add_ghostevent(wm, win, type, time, data);
1275                                 break;
1276                         }
1277                         case GHOST_kEventCursorMove:
1278                         {
1279                                 GHOST_TEventCursorData *cd = data;
1280                                 
1281                                 wm_cursor_position_from_ghost(win, &cd->x, &cd->y);
1282                                 wm_event_add_ghostevent(wm, win, type, time, data);
1283                                 break;
1284                         }
1285                         default:
1286                                 wm_event_add_ghostevent(wm, win, type, time, data);
1287                                 break;
1288                 }
1289
1290         }
1291         return 1;
1292 }
1293
1294
1295 /**
1296  * This timer system only gives maximum 1 timer event per redraw cycle,
1297  * to prevent queues to get overloaded.
1298  * Timer handlers should check for delta to decide if they just update, or follow real time.
1299  * Timer handlers can also set duration to match frames passed
1300  */
1301 static int wm_window_timer(const bContext *C)
1302 {
1303         wmWindowManager *wm = CTX_wm_manager(C);
1304         wmTimer *wt, *wtnext;
1305         wmWindow *win;
1306         double time = PIL_check_seconds_timer();
1307         int retval = 0;
1308         
1309         for (wt = wm->timers.first; wt; wt = wtnext) {
1310                 wtnext = wt->next; /* in case timer gets removed */
1311                 win = wt->win;
1312
1313                 if (wt->sleep == 0) {
1314                         if (time > wt->ntime) {
1315                                 wt->delta = time - wt->ltime;
1316                                 wt->duration += wt->delta;
1317                                 wt->ltime = time;
1318                                 wt->ntime = wt->stime + wt->timestep * ceil(wt->duration / wt->timestep);
1319
1320                                 if (wt->event_type == TIMERJOBS)
1321                                         wm_jobs_timer(C, wm, wt);
1322                                 else if (wt->event_type == TIMERAUTOSAVE)
1323                                         wm_autosave_timer(C, wm, wt);
1324                                 else if (wt->event_type == TIMERNOTIFIER)
1325                                         WM_main_add_notifier(GET_UINT_FROM_POINTER(wt->customdata), NULL);
1326                                 else if (win) {
1327                                         wmEvent event;
1328                                         wm_event_init_from_window(win, &event);
1329                                         
1330                                         event.type = wt->event_type;
1331                                         event.val = KM_NOTHING;
1332                                         event.keymodifier = 0;
1333                                         event.custom = EVT_DATA_TIMER;
1334                                         event.customdata = wt;
1335                                         wm_event_add(win, &event);
1336
1337                                         retval = 1;
1338                                 }
1339                         }
1340                 }
1341         }
1342         return retval;
1343 }
1344
1345 void wm_window_process_events(const bContext *C) 
1346 {
1347         int hasevent;
1348
1349         BLI_assert(BLI_thread_is_main());
1350
1351         hasevent = GHOST_ProcessEvents(g_system, 0); /* 0 is no wait */
1352
1353         if (hasevent)
1354                 GHOST_DispatchEvents(g_system);
1355         
1356         hasevent |= wm_window_timer(C);
1357
1358         /* no event, we sleep 5 milliseconds */
1359         if (hasevent == 0)
1360                 PIL_sleep_ms(5);
1361 }
1362
1363 void wm_window_process_events_nosleep(void) 
1364 {
1365         if (GHOST_ProcessEvents(g_system, 0))
1366                 GHOST_DispatchEvents(g_system);
1367 }
1368
1369 /* exported as handle callback to bke blender.c */
1370 void wm_window_testbreak(void)
1371 {
1372         static double ltime = 0;
1373         double curtime = PIL_check_seconds_timer();
1374
1375         BLI_assert(BLI_thread_is_main());
1376
1377         /* only check for breaks every 50 milliseconds
1378          * if we get called more often.
1379          */
1380         if ((curtime - ltime) > 0.05) {
1381                 int hasevent = GHOST_ProcessEvents(g_system, 0); /* 0 is no wait */
1382                 
1383                 if (hasevent)
1384                         GHOST_DispatchEvents(g_system);
1385                 
1386                 ltime = curtime;
1387         }
1388 }
1389
1390 /* **************** init ********************** */
1391
1392 void wm_ghost_init(bContext *C)
1393 {
1394         if (!g_system) {
1395                 GHOST_EventConsumerHandle consumer = GHOST_CreateEventConsumer(ghost_event_proc, C);
1396                 
1397                 g_system = GHOST_CreateSystem();
1398                 GHOST_AddEventConsumer(g_system, consumer);
1399                 
1400                 if (wm_init_state.native_pixels) {
1401                         GHOST_UseNativePixels();
1402                 }
1403         }
1404 }
1405
1406 void wm_ghost_exit(void)
1407 {
1408         if (g_system)
1409                 GHOST_DisposeSystem(g_system);
1410
1411         g_system = NULL;
1412 }
1413
1414 /* **************** timer ********************** */
1415
1416 /* to (de)activate running timers temporary */
1417 void WM_event_timer_sleep(wmWindowManager *wm, wmWindow *UNUSED(win), wmTimer *timer, bool do_sleep)
1418 {
1419         wmTimer *wt;
1420         
1421         for (wt = wm->timers.first; wt; wt = wt->next)
1422                 if (wt == timer)
1423                         break;
1424
1425         if (wt)
1426                 wt->sleep = do_sleep;
1427 }
1428
1429 wmTimer *WM_event_add_timer(wmWindowManager *wm, wmWindow *win, int event_type, double timestep)
1430 {
1431         wmTimer *wt = MEM_callocN(sizeof(wmTimer), "window timer");
1432
1433         wt->event_type = event_type;
1434         wt->ltime = PIL_check_seconds_timer();
1435         wt->ntime = wt->ltime + timestep;
1436         wt->stime = wt->ltime;
1437         wt->timestep = timestep;
1438         wt->win = win;
1439         
1440         BLI_addtail(&wm->timers, wt);
1441         
1442         return wt;
1443 }
1444
1445 wmTimer *WM_event_add_timer_notifier(wmWindowManager *wm, wmWindow *win, unsigned int type, double timestep)
1446 {
1447         wmTimer *wt = MEM_callocN(sizeof(wmTimer), "window timer");
1448
1449         wt->event_type = TIMERNOTIFIER;
1450         wt->ltime = PIL_check_seconds_timer();
1451         wt->ntime = wt->ltime + timestep;
1452         wt->stime = wt->ltime;
1453         wt->timestep = timestep;
1454         wt->win = win;
1455         wt->customdata = SET_UINT_IN_POINTER(type);
1456
1457         BLI_addtail(&wm->timers, wt);
1458
1459         return wt;
1460 }
1461
1462 void WM_event_remove_timer(wmWindowManager *wm, wmWindow *UNUSED(win), wmTimer *timer)
1463 {
1464         wmTimer *wt;
1465         
1466         /* extra security check */
1467         for (wt = wm->timers.first; wt; wt = wt->next)
1468                 if (wt == timer)
1469                         break;
1470         if (wt) {
1471                 wmWindow *win;
1472                 
1473                 if (wm->reports.reporttimer == wt)
1474                         wm->reports.reporttimer = NULL;
1475                 
1476                 BLI_remlink(&wm->timers, wt);
1477                 if (wt->customdata)
1478                         MEM_freeN(wt->customdata);
1479                 MEM_freeN(wt);
1480                 
1481                 /* there might be events in queue with this timer as customdata */
1482                 for (win = wm->windows.first; win; win = win->next) {
1483                         wmEvent *event;
1484                         for (event = win->queue.first; event; event = event->next) {
1485                                 if (event->customdata == wt) {
1486                                         event->customdata = NULL;
1487                                         event->type = EVENT_NONE;       /* timer users customdata, dont want NULL == NULL */
1488                                 }
1489                         }
1490                 }
1491         }
1492 }
1493
1494 void WM_event_remove_timer_notifier(wmWindowManager *wm, wmWindow *win, wmTimer *timer)
1495 {
1496         timer->customdata = NULL;
1497         WM_event_remove_timer(wm, win, timer);
1498 }
1499
1500 /* ******************* clipboard **************** */
1501
1502 static char *wm_clipboard_text_get_ex(bool selection, int *r_len,
1503                                       bool firstline)
1504 {
1505         char *p, *p2, *buf, *newbuf;
1506
1507         if (G.background) {
1508                 *r_len = 0;
1509                 return NULL;
1510         }
1511
1512         buf = (char *)GHOST_getClipboard(selection);
1513         if (!buf) {
1514                 *r_len = 0;
1515                 return NULL;
1516         }
1517         
1518         /* always convert from \r\n to \n */
1519         p2 = newbuf = MEM_mallocN(strlen(buf) + 1, __func__);
1520
1521         if (firstline) {
1522                 /* will return an over-alloc'ed value in the case there are newlines */
1523                 for (p = buf; *p; p++) {
1524                         if ((*p != '\n') && (*p != '\r')) {
1525                                 *(p2++) = *p;
1526                         }
1527                         else {
1528                                 break;
1529                         }
1530                 }
1531         }
1532         else {
1533                 for (p = buf; *p; p++) {
1534                         if (*p != '\r') {
1535                                 *(p2++) = *p;
1536                         }
1537                 }
1538         }
1539
1540         *p2 = '\0';
1541
1542         free(buf); /* ghost uses regular malloc */
1543         
1544         *r_len = (p2 - newbuf);
1545
1546         return newbuf;
1547 }
1548
1549 /**
1550  * Return text from the clipboard.
1551  *
1552  * \note Caller needs to check for valid utf8 if this is a requirement.
1553  */
1554 char *WM_clipboard_text_get(bool selection, int *r_len)
1555 {
1556         return wm_clipboard_text_get_ex(selection, r_len, false);
1557 }
1558
1559 /**
1560  * Convenience function for pasting to areas of Blender which don't support newlines.
1561  */
1562 char *WM_clipboard_text_get_firstline(bool selection, int *r_len)
1563 {
1564         return wm_clipboard_text_get_ex(selection, r_len, true);
1565 }
1566
1567 void WM_clipboard_text_set(const char *buf, bool selection)
1568 {
1569         if (!G.background) {
1570 #ifdef _WIN32
1571                 /* do conversion from \n to \r\n on Windows */
1572                 const char *p;
1573                 char *p2, *newbuf;
1574                 int newlen = 0;
1575                 
1576                 for (p = buf; *p; p++) {
1577                         if (*p == '\n')
1578                                 newlen += 2;
1579                         else
1580                                 newlen++;
1581                 }
1582                 
1583                 newbuf = MEM_callocN(newlen + 1, "WM_clipboard_text_set");
1584         
1585                 for (p = buf, p2 = newbuf; *p; p++, p2++) {
1586                         if (*p == '\n') {
1587                                 *(p2++) = '\r'; *p2 = '\n';
1588                         }
1589                         else {
1590                                 *p2 = *p;
1591                         }
1592                 }
1593                 *p2 = '\0';
1594         
1595                 GHOST_putClipboard((GHOST_TInt8 *)newbuf, selection);
1596                 MEM_freeN(newbuf);
1597 #else
1598                 GHOST_putClipboard((GHOST_TInt8 *)buf, selection);
1599 #endif
1600         }
1601 }
1602
1603 /* ******************* progress bar **************** */
1604
1605 void WM_progress_set(wmWindow *win, float progress)
1606 {
1607         GHOST_SetProgressBar(win->ghostwin, progress);
1608 }
1609
1610 void WM_progress_clear(wmWindow *win)
1611 {
1612         GHOST_EndProgressBar(win->ghostwin);
1613 }
1614
1615 /* ************************************ */
1616
1617 void wm_window_get_position(wmWindow *win, int *r_pos_x, int *r_pos_y)
1618 {
1619         *r_pos_x = win->posx;
1620         *r_pos_y = win->posy;
1621 }
1622
1623 void wm_window_set_size(wmWindow *win, int width, int height) 
1624 {
1625         GHOST_SetClientSize(win->ghostwin, width, height);
1626 }
1627
1628 void wm_window_lower(wmWindow *win) 
1629 {
1630         GHOST_SetWindowOrder(win->ghostwin, GHOST_kWindowOrderBottom);
1631 }
1632
1633 void wm_window_raise(wmWindow *win) 
1634 {
1635         GHOST_SetWindowOrder(win->ghostwin, GHOST_kWindowOrderTop);
1636 }
1637
1638 void wm_window_swap_buffers(wmWindow *win)
1639 {
1640         
1641 #ifdef WIN32
1642         glDisable(GL_SCISSOR_TEST);
1643         GHOST_SwapWindowBuffers(win->ghostwin);
1644         glEnable(GL_SCISSOR_TEST);
1645 #else
1646         GHOST_SwapWindowBuffers(win->ghostwin);
1647 #endif
1648 }
1649
1650 void wm_window_set_swap_interval (wmWindow *win, int interval)
1651 {
1652         GHOST_SetSwapInterval(win->ghostwin, interval);
1653 }
1654
1655 bool wm_window_get_swap_interval(wmWindow *win, int *intervalOut)
1656 {
1657         return GHOST_GetSwapInterval(win->ghostwin, intervalOut);
1658 }
1659
1660
1661 /* ******************* exported api ***************** */
1662
1663
1664 /* called whem no ghost system was initialized */
1665 void WM_init_state_size_set(int stax, int stay, int sizx, int sizy)
1666 {
1667         wm_init_state.start_x = stax; /* left hand pos */
1668         wm_init_state.start_y = stay; /* bottom pos */
1669         wm_init_state.size_x = sizx < 640 ? 640 : sizx;
1670         wm_init_state.size_y = sizy < 480 ? 480 : sizy;
1671         wm_init_state.override_flag |= WIN_OVERRIDE_GEOM;
1672 }
1673
1674 /* for borderless and border windows set from command-line */
1675 void WM_init_state_fullscreen_set(void)
1676 {
1677         wm_init_state.windowstate = GHOST_kWindowStateFullScreen;
1678         wm_init_state.override_flag |= WIN_OVERRIDE_WINSTATE;
1679 }
1680
1681 void WM_init_state_normal_set(void)
1682 {
1683         wm_init_state.windowstate = GHOST_kWindowStateNormal;
1684         wm_init_state.override_flag |= WIN_OVERRIDE_WINSTATE;
1685 }
1686
1687 void WM_init_native_pixels(bool do_it)
1688 {
1689         wm_init_state.native_pixels = do_it;
1690 }
1691
1692 /* This function requires access to the GHOST_SystemHandle (g_system) */
1693 void WM_cursor_warp(wmWindow *win, int x, int y)
1694 {
1695         if (win && win->ghostwin) {
1696                 int oldx = x, oldy = y;
1697
1698                 wm_cursor_position_to_ghost(win, &x, &y);
1699                 GHOST_SetCursorPosition(g_system, x, y);
1700
1701                 win->eventstate->prevx = oldx;
1702                 win->eventstate->prevy = oldy;
1703
1704                 win->eventstate->x = oldx;
1705                 win->eventstate->y = oldy;
1706         }
1707 }
1708
1709 /**
1710  * Set x, y to values we can actually position the cursor to.
1711  */
1712 void WM_cursor_compatible_xy(wmWindow *win, int *x, int *y)
1713 {
1714         float f = GHOST_GetNativePixelSize(win->ghostwin);
1715         if (f != 1.0f) {
1716                 *x = (int)(*x / f) * f;
1717                 *y = (int)(*y / f) * f;
1718         }
1719 }
1720
1721 /**
1722  * Get the cursor pressure, in most cases you'll want to use wmTabletData from the event
1723  */
1724 float WM_cursor_pressure(const struct wmWindow *win)
1725 {
1726         const GHOST_TabletData *td = GHOST_GetTabletData(win->ghostwin);
1727         /* if there's tablet data from an active tablet device then add it */
1728         if ((td != NULL) && td->Active != GHOST_kTabletModeNone) {
1729                 return td->Pressure;
1730         }
1731         else {
1732                 return -1.0f;
1733         }
1734 }
1735
1736 /* support for native pixel size */
1737 /* mac retina opens window in size X, but it has up to 2 x more pixels */
1738 int WM_window_pixels_x(wmWindow *win)
1739 {
1740         float f = GHOST_GetNativePixelSize(win->ghostwin);
1741         
1742         return (int)(f * (float)win->sizex);
1743 }
1744
1745 int WM_window_pixels_y(wmWindow *win)
1746 {
1747         float f = GHOST_GetNativePixelSize(win->ghostwin);
1748         
1749         return (int)(f * (float)win->sizey);
1750         
1751 }
1752
1753 bool WM_window_is_fullscreen(wmWindow *win)
1754 {
1755         return win->windowstate == GHOST_kWindowStateFullScreen;
1756 }
1757
1758
1759 #ifdef WITH_INPUT_IME
1760 /* note: keep in mind wm_window_IME_begin is also used to reposition the IME window */
1761 void wm_window_IME_begin(wmWindow *win, int x, int y, int w, int h, bool complete)
1762 {
1763         BLI_assert(win);
1764
1765         GHOST_BeginIME(win->ghostwin, x, win->sizey - y, w, h, complete);
1766 }
1767
1768 void wm_window_IME_end(wmWindow *win)
1769 {
1770         BLI_assert(win && win->ime_data);
1771
1772         GHOST_EndIME(win->ghostwin);
1773         win->ime_data = NULL;
1774 }
1775 #endif  /* WITH_INPUT_IME */