style cleanup: changes from recent commits
[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
31
32 #include <math.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36
37 #include "DNA_listBase.h"       
38 #include "DNA_screen_types.h"
39 #include "DNA_windowmanager_types.h"
40 #include "RNA_access.h"
41
42 #include "MEM_guardedalloc.h"
43
44 #include "GHOST_C-api.h"
45
46 #include "BLI_blenlib.h"
47 #include "BLI_utildefines.h"
48
49 #include "BLF_translation.h"
50
51 #include "BKE_blender.h"
52 #include "BKE_context.h"
53 #include "BKE_library.h"
54 #include "BKE_global.h"
55 #include "BKE_main.h"
56
57
58 #include "BIF_gl.h"
59
60 #include "WM_api.h"
61 #include "WM_types.h"
62 #include "wm.h"
63 #include "wm_draw.h"
64 #include "wm_window.h"
65 #include "wm_subwindow.h"
66 #include "wm_event_system.h"
67
68 #include "ED_screen.h"
69 #include "ED_fileselect.h"
70
71 #include "PIL_time.h"
72
73 #include "GPU_draw.h"
74 #include "GPU_extensions.h"
75
76 #include "UI_interface.h"
77
78 /* the global to talk to ghost */
79 static GHOST_SystemHandle g_system = NULL;
80
81 typedef enum WinOverrideFlag {
82         WIN_OVERRIDE_GEOM     = (1 << 0),
83         WIN_OVERRIDE_WINSTATE = (1 << 1)
84 } WinOverrideFlag;
85
86 /* set by commandline */
87 static struct WMInitStruct {
88         /* window geometry */
89         int size_x, size_y;
90         int start_x, start_y;
91
92         int windowstate;
93         WinOverrideFlag override_flag;
94         
95         int native_pixels;
96 } wm_init_state = {0, 0, 0, 0, GHOST_kWindowStateNormal, 0, 1};
97
98 /* ******** win open & close ************ */
99
100 /* XXX this one should correctly check for apple top header...
101  * done for Cocoa : returns window contents (and not frame) max size*/
102 void wm_get_screensize(int *width_r, int *height_r)
103 {
104         unsigned int uiwidth;
105         unsigned int uiheight;
106         
107         GHOST_GetMainDisplayDimensions(g_system, &uiwidth, &uiheight);
108         *width_r = uiwidth;
109         *height_r = uiheight;
110 }
111
112 /* keeps offset and size within monitor bounds */
113 /* XXX solve dual screen... */
114 static void wm_window_check_position(rcti *rect)
115 {
116         int width, height, d;
117         
118         wm_get_screensize(&width, &height);
119         
120 #if defined(__APPLE__) && !defined(GHOST_COCOA)
121         height -= 70;
122 #endif
123         
124         if (rect->xmin < 0) {
125                 rect->xmax -= rect->xmin;
126                 rect->xmin  = 0;
127         }
128         if (rect->ymin < 0) {
129                 rect->ymax -= rect->ymin;
130                 rect->ymin  = 0;
131         }
132         if (rect->xmax > width) {
133                 d = rect->xmax - width;
134                 rect->xmax -= d;
135                 rect->xmin -= d;
136         }
137         if (rect->ymax > height) {
138                 d = rect->ymax - height;
139                 rect->ymax -= d;
140                 rect->ymin -= d;
141         }
142         
143         if (rect->xmin < 0) rect->xmin = 0;
144         if (rect->ymin < 0) rect->ymin = 0;
145 }
146
147
148 static void wm_ghostwindow_destroy(wmWindow *win) 
149 {
150         if (win->ghostwin) {
151                 GHOST_DisposeWindow(g_system, win->ghostwin);
152                 win->ghostwin = NULL;
153         }
154 }
155
156 /* including window itself, C can be NULL. 
157  * ED_screen_exit should have been called */
158 void wm_window_free(bContext *C, wmWindowManager *wm, wmWindow *win)
159 {
160         wmTimer *wt, *wtnext;
161         
162         /* update context */
163         if (C) {
164                 WM_event_remove_handlers(C, &win->handlers);
165                 WM_event_remove_handlers(C, &win->modalhandlers);
166
167                 if (CTX_wm_window(C) == win)
168                         CTX_wm_window_set(C, NULL);
169         }
170
171         /* always set drawable and active to NULL,
172          * prevents non-drawable state of main windows (bugs #22967 and #25071, possibly #22477 too) */
173         wm->windrawable = NULL;
174         wm->winactive = NULL;
175
176         /* end running jobs, a job end also removes its timer */
177         for (wt = wm->timers.first; wt; wt = wtnext) {
178                 wtnext = wt->next;
179                 if (wt->win == win && wt->event_type == TIMERJOBS)
180                         wm_jobs_timer_ended(wm, wt);
181         }
182         
183         /* timer removing, need to call this api function */
184         for (wt = wm->timers.first; wt; wt = wtnext) {
185                 wtnext = wt->next;
186                 if (wt->win == win)
187                         WM_event_remove_timer(wm, win, wt);
188         }
189
190         if (win->eventstate) MEM_freeN(win->eventstate);
191         
192         wm_event_free_all(win);
193         wm_subwindows_free(win);
194         
195         if (win->drawdata)
196                 MEM_freeN(win->drawdata);
197         
198         wm_ghostwindow_destroy(win);
199         
200         MEM_freeN(win);
201 }
202
203 static int find_free_winid(wmWindowManager *wm)
204 {
205         wmWindow *win;
206         int id = 1;
207         
208         for (win = wm->windows.first; win; win = win->next)
209                 if (id <= win->winid)
210                         id = win->winid + 1;
211         
212         return id;
213 }
214
215 /* don't change context itself */
216 wmWindow *wm_window_new(bContext *C)
217 {
218         wmWindowManager *wm = CTX_wm_manager(C);
219         wmWindow *win = MEM_callocN(sizeof(wmWindow), "window");
220         
221         BLI_addtail(&wm->windows, win);
222         win->winid = find_free_winid(wm);
223
224         return win;
225 }
226
227
228 /* part of wm_window.c api */
229 wmWindow *wm_window_copy(bContext *C, wmWindow *winorig)
230 {
231         wmWindow *win = wm_window_new(C);
232         
233         win->posx = winorig->posx + 10;
234         win->posy = winorig->posy;
235         win->sizex = winorig->sizex;
236         win->sizey = winorig->sizey;
237         
238         /* duplicate assigns to window */
239         win->screen = ED_screen_duplicate(win, winorig->screen);
240         BLI_strncpy(win->screenname, win->screen->id.name + 2, sizeof(win->screenname));
241         win->screen->winid = win->winid;
242
243         win->screen->do_refresh = TRUE;
244         win->screen->do_draw = TRUE;
245
246         win->drawmethod = U.wmdrawmethod;
247         win->drawdata = NULL;
248         
249         return win;
250 }
251
252 /* this is event from ghost, or exit-blender op */
253 void wm_window_close(bContext *C, wmWindowManager *wm, wmWindow *win)
254 {
255         wmWindow *tmpwin;
256         int do_exit = 0;
257         
258         /* first check if we have to quit (there are non-temp remaining windows) */
259         for (tmpwin = wm->windows.first; tmpwin; tmpwin = tmpwin->next) {
260                 if (tmpwin == win)
261                         continue;
262                 if (tmpwin->screen->temp == 0)
263                         break;
264         }
265
266         if (tmpwin == NULL)
267                 do_exit = 1;
268         
269         if ((U.uiflag & USER_QUIT_PROMPT) && !wm->file_saved) {
270                 if (do_exit) {
271                         if (!GHOST_confirmQuit(win->ghostwin))
272                                 return;
273                 }
274         }
275
276         /* let WM_exit do all freeing, for correct quit.blend save */
277         if (do_exit) {
278                 WM_exit(C);
279         }
280         else {
281                 bScreen *screen = win->screen;
282                 
283                 BLI_remlink(&wm->windows, win);
284                 
285                 wm_draw_window_clear(win);
286                 
287                 CTX_wm_window_set(C, win);  /* needed by handlers */
288                 WM_event_remove_handlers(C, &win->handlers);
289                 WM_event_remove_handlers(C, &win->modalhandlers);
290                 ED_screen_exit(C, win, win->screen); 
291                 
292                 wm_window_free(C, wm, win);
293         
294                 /* if temp screen, delete it after window free (it stops jobs that can access it) */
295                 if (screen->temp) {
296                         Main *bmain = CTX_data_main(C);
297                         BKE_libblock_free(&bmain->screen, screen);
298                 }
299         }               
300 }
301
302 void wm_window_title(wmWindowManager *wm, wmWindow *win)
303 {
304         if (win->screen && win->screen->temp) {
305                 /* nothing to do for 'temp' windows,
306                  * because WM_window_open_temp always sets window title  */
307         }
308         else {
309                 
310                 /* this is set to 1 if you don't have startup.blend open */
311                 if (G.save_over && G.main->name[0]) {
312                         char str[sizeof(G.main->name) + 12];
313                         BLI_snprintf(str, sizeof(str), "Blender%s [%s%s]", wm->file_saved ? "" : "*", G.main->name,
314                                      G.main->recovered ? " (Recovered)" : "");
315                         GHOST_SetTitle(win->ghostwin, str);
316                 }
317                 else
318                         GHOST_SetTitle(win->ghostwin, "Blender");
319
320                 /* Informs GHOST of unsaved changes, to set window modified visual indicator (MAC OS X)
321                  * and to give hint of unsaved changes for a user warning mechanism
322                  * in case of OS application terminate request (e.g. OS Shortcut Alt+F4, Cmd+Q, (...), or session end) */
323                 GHOST_SetWindowModifiedState(win->ghostwin, (GHOST_TUns8) !wm->file_saved);
324                 
325 #if defined(__APPLE__) && !defined(GHOST_COCOA)
326                 if (wm->file_saved)
327                         GHOST_SetWindowState(win->ghostwin, GHOST_kWindowStateUnModified);
328                 else
329                         GHOST_SetWindowState(win->ghostwin, GHOST_kWindowStateModified);
330 #endif
331         }
332 }
333
334 /* belongs to below */
335 static void wm_window_add_ghostwindow(const char *title, wmWindow *win)
336 {
337         GHOST_WindowHandle ghostwin;
338         static int multisamples = -1;
339         int scr_w, scr_h, posy;
340         
341         /* force setting multisamples only once, it requires restart - and you cannot 
342          * mix it, either all windows have it, or none (tested in OSX opengl) */
343         if (multisamples == -1)
344                 multisamples = U.ogl_multisamples;
345         
346         wm_get_screensize(&scr_w, &scr_h);
347         posy = (scr_h - win->posy - win->sizey);
348         
349         ghostwin = GHOST_CreateWindow(g_system, title,
350                                       win->posx, posy, win->sizex, win->sizey,
351                                       (GHOST_TWindowState)win->windowstate,
352                                       GHOST_kDrawingContextTypeOpenGL,
353                                       0 /* no stereo */,
354                                       multisamples /* AA */);
355         
356         if (ghostwin) {
357                 GHOST_RectangleHandle bounds;
358                 
359                 /* needed so we can detect the graphics card below */
360                 GPU_extensions_init();
361                 
362                 /* set the state*/
363                 GHOST_SetWindowState(ghostwin, (GHOST_TWindowState)win->windowstate);
364
365                 win->ghostwin = ghostwin;
366                 GHOST_SetWindowUserData(ghostwin, win); /* pointer back */
367                 
368                 if (win->eventstate == NULL)
369                         win->eventstate = MEM_callocN(sizeof(wmEvent), "window event state");
370                 
371                 /* until screens get drawn, make it nice gray */
372                 glClearColor(0.55, 0.55, 0.55, 0.0);
373                 /* Crash on OSS ATI: bugs.launchpad.net/ubuntu/+source/mesa/+bug/656100 */
374                 if (!GPU_type_matches(GPU_DEVICE_ATI, GPU_OS_UNIX, GPU_DRIVER_OPENSOURCE)) {
375                         glClear(GL_COLOR_BUFFER_BIT);
376                 }
377                 
378                 /* displays with larger native pixels, like Macbook. Used to scale dpi with */
379                 /* needed here, because it's used before it reads userdef */
380                 U.pixelsize = GHOST_GetNativePixelSize();
381                 BKE_userdef_state();
382                 
383                 /* store actual window size in blender window */
384                 bounds = GHOST_GetClientBounds(win->ghostwin);
385                 win->sizex = GHOST_GetWidthRectangle(bounds);
386                 win->sizey = GHOST_GetHeightRectangle(bounds);
387                 GHOST_DisposeRectangle(bounds);
388
389                 
390                 wm_window_swap_buffers(win);
391                 
392                 //GHOST_SetWindowState(ghostwin, GHOST_kWindowStateModified);
393                 
394                 /* standard state vars for window */
395                 glEnable(GL_SCISSOR_TEST);
396                 GPU_state_init();
397         }
398 }
399
400 /* for wmWindows without ghostwin, open these and clear */
401 /* window size is read from window, if 0 it uses prefsize */
402 /* called in WM_check, also inits stuff after file read */
403 void wm_window_add_ghostwindows(wmWindowManager *wm)
404 {
405         wmKeyMap *keymap;
406         wmWindow *win;
407         
408         /* no commandline prefsize? then we set this.
409          * Note that these values will be used only
410          * when there is no startup.blend yet.
411          */
412         if (wm_init_state.size_x == 0) {
413                 wm_get_screensize(&wm_init_state.size_x, &wm_init_state.size_y);
414                 
415 #if defined(__APPLE__) && !defined(GHOST_COCOA)
416                 /* Cocoa provides functions to get correct max window size */
417                 {
418                         extern void wm_set_apple_prefsize(int, int);    /* wm_apple.c */
419                         
420                         wm_set_apple_prefsize(wm_init_state.size_x, wm_init_state.size_y);
421                 }
422 #else
423                 wm_init_state.start_x = 0;
424                 wm_init_state.start_y = 0;
425                 
426 #endif
427         }
428         
429         for (win = wm->windows.first; win; win = win->next) {
430                 if (win->ghostwin == NULL) {
431                         if ((win->sizex == 0) || (wm_init_state.override_flag & WIN_OVERRIDE_GEOM)) {
432                                 win->posx = wm_init_state.start_x;
433                                 win->posy = wm_init_state.start_y;
434                                 win->sizex = wm_init_state.size_x;
435                                 win->sizey = wm_init_state.size_y;
436
437                                 /* we can't properly resize a maximized window */
438                                 win->windowstate = GHOST_kWindowStateNormal;
439
440                                 wm_init_state.override_flag &= ~WIN_OVERRIDE_GEOM;
441                         }
442
443                         if (wm_init_state.override_flag & WIN_OVERRIDE_WINSTATE) {
444                                 win->windowstate = wm_init_state.windowstate;
445                                 wm_init_state.override_flag &= ~WIN_OVERRIDE_WINSTATE;
446                         }
447
448                         wm_window_add_ghostwindow("Blender", win);
449                 }
450                 /* happens after fileread */
451                 if (win->eventstate == NULL)
452                         win->eventstate = MEM_callocN(sizeof(wmEvent), "window event state");
453
454                 /* add keymap handlers (1 handler for all keys in map!) */
455                 keymap = WM_keymap_find(wm->defaultconf, "Window", 0, 0);
456                 WM_event_add_keymap_handler(&win->handlers, keymap);
457                 
458                 keymap = WM_keymap_find(wm->defaultconf, "Screen", 0, 0);
459                 WM_event_add_keymap_handler(&win->handlers, keymap);
460
461                 keymap = WM_keymap_find(wm->defaultconf, "Screen Editing", 0, 0);
462                 WM_event_add_keymap_handler(&win->modalhandlers, keymap);
463                 
464                 /* add drop boxes */
465                 {
466                         ListBase *lb = WM_dropboxmap_find("Window", 0, 0);
467                         WM_event_add_dropbox_handler(&win->handlers, lb);
468                 }
469                 wm_window_title(wm, win);
470         }
471 }
472
473 /* new window, no screen yet, but we open ghostwindow for it */
474 /* also gets the window level handlers */
475 /* area-rip calls this */
476 wmWindow *WM_window_open(bContext *C, rcti *rect)
477 {
478         wmWindow *win = wm_window_new(C);
479         
480         win->posx = rect->xmin;
481         win->posy = rect->ymin;
482         win->sizex = BLI_rcti_size_x(rect);
483         win->sizey = BLI_rcti_size_y(rect);
484
485         win->drawmethod = U.wmdrawmethod;
486         win->drawdata = NULL;
487         
488         WM_check(C);
489         
490         return win;
491 }
492
493 /* uses screen->temp tag to define what to do, currently it limits
494  * to only one "temp" window for render out, preferences, filewindow, etc */
495 /* type is defined in WM_api.h */
496
497 void WM_window_open_temp(bContext *C, rcti *position, int type)
498 {
499         wmWindow *win;
500         ScrArea *sa;
501         
502         /* changes rect to fit within desktop */
503         wm_window_check_position(position);
504         
505         /* test if we have a temp screen already */
506         for (win = CTX_wm_manager(C)->windows.first; win; win = win->next)
507                 if (win->screen->temp)
508                         break;
509         
510         /* add new window? */
511         if (win == NULL) {
512                 win = wm_window_new(C);
513                 
514                 win->posx = position->xmin;
515                 win->posy = position->ymin;
516         }
517         
518         win->sizex = BLI_rcti_size_x(position);
519         win->sizey = BLI_rcti_size_y(position);
520         
521         if (win->ghostwin) {
522                 wm_window_set_size(win, win->sizex, win->sizey);
523                 wm_window_raise(win);
524         }
525         
526         /* add new screen? */
527         if (win->screen == NULL)
528                 win->screen = ED_screen_add(win, CTX_data_scene(C), "temp");
529         win->screen->temp = 1; 
530         
531         /* make window active, and validate/resize */
532         CTX_wm_window_set(C, win);
533         WM_check(C);
534         
535         /* ensure it shows the right spacetype editor */
536         sa = win->screen->areabase.first;
537         CTX_wm_area_set(C, sa);
538         
539         if (type == WM_WINDOW_RENDER) {
540                 ED_area_newspace(C, sa, SPACE_IMAGE);
541         }
542         else {
543                 ED_area_newspace(C, sa, SPACE_USERPREF);
544         }
545         
546         ED_screen_set(C, win->screen);
547         
548         if (sa->spacetype == SPACE_IMAGE)
549                 GHOST_SetTitle(win->ghostwin, IFACE_("Blender Render"));
550         else if (ELEM(sa->spacetype, SPACE_OUTLINER, SPACE_USERPREF))
551                 GHOST_SetTitle(win->ghostwin, IFACE_("Blender User Preferences"));
552         else if (sa->spacetype == SPACE_FILE)
553                 GHOST_SetTitle(win->ghostwin, IFACE_("Blender File View"));
554         else
555                 GHOST_SetTitle(win->ghostwin, "Blender");
556 }
557
558
559 /* ****************** Operators ****************** */
560
561 /* operator callback */
562 int wm_window_duplicate_exec(bContext *C, wmOperator *UNUSED(op))
563 {
564         wm_window_copy(C, CTX_wm_window(C));
565         WM_check(C);
566         
567         WM_event_add_notifier(C, NC_WINDOW | NA_ADDED, NULL);
568         
569         return OPERATOR_FINISHED;
570 }
571
572
573 /* fullscreen operator callback */
574 int wm_window_fullscreen_toggle_exec(bContext *C, wmOperator *UNUSED(op))
575 {
576         wmWindow *window = CTX_wm_window(C);
577         GHOST_TWindowState state;
578
579         if (G.background)
580                 return OPERATOR_CANCELLED;
581
582         state = GHOST_GetWindowState(window->ghostwin);
583         if (state != GHOST_kWindowStateFullScreen)
584                 GHOST_SetWindowState(window->ghostwin, GHOST_kWindowStateFullScreen);
585         else
586                 GHOST_SetWindowState(window->ghostwin, GHOST_kWindowStateNormal);
587
588         return OPERATOR_FINISHED;
589         
590 }
591
592
593 /* ************ events *************** */
594
595 static void wm_convert_cursor_position(wmWindow *win, int *x, int *y)
596 {
597
598         GHOST_ScreenToClient(win->ghostwin, *x, *y, x, y);
599         *x *= GHOST_GetNativePixelSize();
600         
601         *y = (win->sizey - 1) - *y;
602         *y *= GHOST_GetNativePixelSize();
603 }
604
605
606 void wm_get_cursor_position(wmWindow *win, int *x, int *y)
607 {
608         GHOST_GetCursorPosition(g_system, x, y);
609         wm_convert_cursor_position(win, x, y);
610 }
611
612 typedef enum {
613         SHIFT    = 's',
614         CONTROL  = 'c',
615         ALT      = 'a',
616         OS       = 'C'
617 } modifierKeyType;
618
619 /* check if specified modifier key type is pressed */
620 static int query_qual(modifierKeyType qual) 
621 {
622         GHOST_TModifierKeyMask left, right;
623         int val = 0;
624         
625         switch (qual) {
626                 case SHIFT:
627                         left = GHOST_kModifierKeyLeftShift;
628                         right = GHOST_kModifierKeyRightShift;
629                         break;
630                 case CONTROL:
631                         left = GHOST_kModifierKeyLeftControl;
632                         right = GHOST_kModifierKeyRightControl;
633                         break;
634                 case OS:
635                         left = right = GHOST_kModifierKeyOS;
636                         break;
637                 case ALT:
638                 default:
639                         left = GHOST_kModifierKeyLeftAlt;
640                         right = GHOST_kModifierKeyRightAlt;
641                         break;
642         }
643         
644         GHOST_GetModifierKeyState(g_system, left, &val);
645         if (!val)
646                 GHOST_GetModifierKeyState(g_system, right, &val);
647         
648         return val;
649 }
650
651 void wm_window_make_drawable(bContext *C, wmWindow *win) 
652 {
653         wmWindowManager *wm = CTX_wm_manager(C);
654
655         if (win != wm->windrawable && win->ghostwin) {
656 //              win->lmbut = 0; /* keeps hanging when mousepressed while other window opened */
657                 
658                 wm->windrawable = win;
659                 if (G.debug & G_DEBUG_EVENTS) {
660                         printf("%s: set drawable %d\n", __func__, win->winid);
661                 }
662                 GHOST_ActivateWindowDrawingContext(win->ghostwin);
663         }
664 }
665
666 /* called by ghost, here we handle events for windows themselves or send to event system */
667 /* mouse coordinate converversion happens here */
668 static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr)
669 {
670         bContext *C = C_void_ptr;
671         wmWindowManager *wm = CTX_wm_manager(C);
672         GHOST_TEventType type = GHOST_GetEventType(evt);
673         int time = GHOST_GetEventTime(evt);
674         
675         if (type == GHOST_kEventQuit) {
676                 WM_exit(C);
677         }
678         else {
679                 GHOST_WindowHandle ghostwin = GHOST_GetEventWindow(evt);
680                 GHOST_TEventDataPtr data = GHOST_GetEventData(evt);
681                 wmWindow *win;
682                 
683                 if (!ghostwin) {
684                         /* XXX - should be checked, why are we getting an event here, and */
685                         /* what is it? */
686                         puts("<!> event has no window");
687                         return 1;
688                 }
689                 else if (!GHOST_ValidWindow(g_system, ghostwin)) {
690                         /* XXX - should be checked, why are we getting an event here, and */
691                         /* what is it? */
692                         puts("<!> event has invalid window");
693                         return 1;
694                 }
695                 else {
696                         win = GHOST_GetWindowUserData(ghostwin);
697                 }
698                 
699                 switch (type) {
700                         case GHOST_kEventWindowDeactivate:
701                                 wm_event_add_ghostevent(wm, win, type, time, data);
702                                 win->active = 0; /* XXX */
703                                 break;
704                         case GHOST_kEventWindowActivate: 
705                         {
706                                 GHOST_TEventKeyData kdata;
707                                 wmEvent event;
708                                 int wx, wy;
709                                 
710                                 wm->winactive = win; /* no context change! c->wm->windrawable is drawable, or for area queues */
711                                 
712                                 win->active = 1;
713 //                              window_handle(win, INPUTCHANGE, win->active);
714                                 
715                                 /* bad ghost support for modifier keys... so on activate we set the modifiers again */
716                                 kdata.ascii = '\0';
717                                 kdata.utf8_buf[0] = '\0';
718                                 if (win->eventstate->shift && !query_qual(SHIFT)) {
719                                         kdata.key = GHOST_kKeyLeftShift;
720                                         wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
721                                 }
722                                 if (win->eventstate->ctrl && !query_qual(CONTROL)) {
723                                         kdata.key = GHOST_kKeyLeftControl;
724                                         wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
725                                 }
726                                 if (win->eventstate->alt && !query_qual(ALT)) {
727                                         kdata.key = GHOST_kKeyLeftAlt;
728                                         wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
729                                 }
730                                 if (win->eventstate->oskey && !query_qual(OS)) {
731                                         kdata.key = GHOST_kKeyOS;
732                                         wm_event_add_ghostevent(wm, win, GHOST_kEventKeyUp, time, &kdata);
733                                 }
734                                 /* keymodifier zero, it hangs on hotkeys that open windows otherwise */
735                                 win->eventstate->keymodifier = 0;
736                                 
737                                 /* entering window, update mouse pos. but no event */
738                                 wm_get_cursor_position(win,  &wx, &wy);
739
740                                 win->eventstate->x = wx;
741                                 win->eventstate->y = wy;
742                                 
743                                 win->addmousemove = 1;   /* enables highlighted buttons */
744                                 
745                                 wm_window_make_drawable(C, win);
746
747                                 /* window might be focused by mouse click in configuration of window manager
748                                  * when focus is not following mouse
749                                  * click could have been done on a button and depending on window manager settings
750                                  * click would be passed to blender or not, but in any case button under cursor
751                                  * should be activated, so at max next click on button without moving mouse
752                                  * would trigger it's handle function
753                                  * currently it seems to be common practice to generate new event for, but probably
754                                  * we'll need utility function for this? (sergey)
755                                  */
756                                 event = *(win->eventstate);
757                                 event.type = MOUSEMOVE;
758                                 event.prevx = event.x;
759                                 event.prevy = event.y;
760
761                                 wm_event_add(win, &event);
762
763                                 break;
764                         }
765                         case GHOST_kEventWindowClose:
766                         {
767                                 wm_window_close(C, wm, win);
768                                 break;
769                         }
770                         case GHOST_kEventWindowUpdate:
771                         {
772                                 if (G.debug & G_DEBUG_EVENTS) {
773                                         printf("%s: ghost redraw %d\n", __func__, win->winid);
774                                 }
775                                 
776                                 wm_window_make_drawable(C, win);
777                                 WM_event_add_notifier(C, NC_WINDOW, NULL);
778
779                                 break;
780                         }
781                         case GHOST_kEventWindowSize:
782                         case GHOST_kEventWindowMove:
783                         {
784                                 GHOST_TWindowState state;
785                                 state = GHOST_GetWindowState(win->ghostwin);
786                                 win->windowstate = state;
787
788                                 /* stop screencast if resize */
789                                 if (type == GHOST_kEventWindowSize) {
790                                         WM_jobs_stop(CTX_wm_manager(C), win->screen, NULL);
791                                 }
792                                 
793                                 /* win32: gives undefined window size when minimized */
794                                 if (state != GHOST_kWindowStateMinimized) {
795                                         GHOST_RectangleHandle client_rect;
796                                         int l, t, r, b, scr_w, scr_h;
797                                         int sizex, sizey, posx, posy;
798                                         
799                                         client_rect = GHOST_GetClientBounds(win->ghostwin);
800                                         GHOST_GetRectangle(client_rect, &l, &t, &r, &b);
801                                         
802                                         GHOST_DisposeRectangle(client_rect);
803                                         
804                                         wm_get_screensize(&scr_w, &scr_h);
805                                         sizex = r - l;
806                                         sizey = b - t;
807                                         posx = l;
808                                         posy = scr_h - t - win->sizey;
809
810                                         /*
811                                          * Ghost sometimes send size or move events when the window hasn't changed.
812                                          * One case of this is using compiz on linux. To alleviate the problem
813                                          * we ignore all such event here.
814                                          * 
815                                          * It might be good to eventually do that at Ghost level, but that is for 
816                                          * another time.
817                                          */
818                                         if (win->sizex != sizex ||
819                                             win->sizey != sizey ||
820                                             win->posx != posx ||
821                                             win->posy != posy)
822                                         {
823                                                 win->sizex = sizex;
824                                                 win->sizey = sizey;
825                                                 win->posx = posx;
826                                                 win->posy = posy;
827
828                                                 /* debug prints */
829                                                 if (G.debug & G_DEBUG_EVENTS) {
830                                                         const char *state_str;
831                                                         state = GHOST_GetWindowState(win->ghostwin);
832
833                                                         if (state == GHOST_kWindowStateNormal) {
834                                                                 state_str = "normal";
835                                                         }
836                                                         else if (state == GHOST_kWindowStateMinimized) {
837                                                                 state_str = "minimized";
838                                                         }
839                                                         else if (state == GHOST_kWindowStateMaximized) {
840                                                                 state_str = "maximized";
841                                                         }
842                                                         else if (state == GHOST_kWindowStateFullScreen) {
843                                                                 state_str = "fullscreen";
844                                                         }
845                                                         else {
846                                                                 state_str = "<unknown>";
847                                                         }
848
849                                                         printf("%s: window %d state = %s\n", __func__, win->winid, state_str);
850
851                                                         if (type != GHOST_kEventWindowSize) {
852                                                                 printf("win move event pos %d %d size %d %d\n",
853                                                                        win->posx, win->posy, win->sizex, win->sizey);
854                                                         }
855                                                 }
856                                         
857                                                 wm_window_make_drawable(C, win);
858                                                 wm_draw_window_clear(win);
859                                                 WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
860                                                 WM_event_add_notifier(C, NC_WINDOW | NA_EDITED, NULL);
861                                         }
862                                 }
863                                 break;
864                         }
865                                 
866                         case GHOST_kEventOpenMainFile:
867                         {
868                                 PointerRNA props_ptr;
869                                 wmWindow *oldWindow;
870                                 char *path = GHOST_GetEventData(evt);
871                                 
872                                 if (path) {
873                                         /* operator needs a valid window in context, ensures
874                                          * it is correctly set */
875                                         oldWindow = CTX_wm_window(C);
876                                         CTX_wm_window_set(C, win);
877                                         
878                                         WM_operator_properties_create(&props_ptr, "WM_OT_open_mainfile");
879                                         RNA_string_set(&props_ptr, "filepath", path);
880                                         WM_operator_name_call(C, "WM_OT_open_mainfile", WM_OP_EXEC_DEFAULT, &props_ptr);
881                                         WM_operator_properties_free(&props_ptr);
882                                         
883                                         CTX_wm_window_set(C, oldWindow);
884                                 }
885                                 break;
886                         }
887                         case GHOST_kEventDraggingDropDone:
888                         {
889                                 wmEvent event;
890                                 GHOST_TEventDragnDropData *ddd = GHOST_GetEventData(evt);
891                                 int wx, wy;
892                                 
893                                 /* entering window, update mouse pos */
894                                 wm_get_cursor_position(win, &wx, &wy);
895                                 win->eventstate->x = wx;
896                                 win->eventstate->y = wy;
897                                 
898                                 event = *(win->eventstate);  /* copy last state, like mouse coords */
899                                 
900                                 /* activate region */
901                                 event.type = MOUSEMOVE;
902                                 event.prevx = event.x;
903                                 event.prevy = event.y;
904                                 
905                                 wm->winactive = win; /* no context change! c->wm->windrawable is drawable, or for area queues */
906                                 win->active = 1;
907                                 
908                                 wm_event_add(win, &event);
909                                 
910                                 
911                                 /* make blender drop event with custom data pointing to wm drags */
912                                 event.type = EVT_DROP;
913                                 event.val = KM_RELEASE;
914                                 event.custom = EVT_DATA_LISTBASE;
915                                 event.customdata = &wm->drags;
916                                 event.customdatafree = 1;
917                                 
918                                 wm_event_add(win, &event);
919                                 
920                                 /* printf("Drop detected\n"); */
921                                 
922                                 /* add drag data to wm for paths: */
923                                 
924                                 if (ddd->dataType == GHOST_kDragnDropTypeFilenames) {
925                                         GHOST_TStringArray *stra = ddd->data;
926                                         int a, icon;
927                                         
928                                         for (a = 0; a < stra->count; a++) {
929                                                 printf("drop file %s\n", stra->strings[a]);
930                                                 /* try to get icon type from extension */
931                                                 icon = ED_file_extension_icon((char *)stra->strings[a]);
932                                                 
933                                                 WM_event_start_drag(C, icon, WM_DRAG_PATH, stra->strings[a], 0.0);
934                                                 /* void poin should point to string, it makes a copy */
935                                                 break; /* only one drop element supported now */
936                                         }
937                                 }
938                                 
939                                 break;
940                         }
941                         case GHOST_kEventTrackpad:
942                         {
943                                 GHOST_TEventTrackpadData *pd = data;
944                                 
945                                 wm_convert_cursor_position(win, &pd->x, &pd->y);
946                                 wm_event_add_ghostevent(wm, win, type, time, data);
947                                 break;
948                         }
949                         case GHOST_kEventCursorMove:
950                         {
951                                 GHOST_TEventCursorData *cd = data;
952                                 
953                                 wm_convert_cursor_position(win, &cd->x, &cd->y);
954                                 wm_event_add_ghostevent(wm, win, type, time, data);
955                                 break;
956                         }
957                         default:
958                                 wm_event_add_ghostevent(wm, win, type, time, data);
959                                 break;
960                 }
961
962         }
963         return 1;
964 }
965
966
967 /* This timer system only gives maximum 1 timer event per redraw cycle,
968  * to prevent queues to get overloaded.
969  * Timer handlers should check for delta to decide if they just
970  * update, or follow real time.
971  * Timer handlers can also set duration to match frames passed
972  */
973 static int wm_window_timer(const bContext *C)
974 {
975         wmWindowManager *wm = CTX_wm_manager(C);
976         wmTimer *wt, *wtnext;
977         wmWindow *win;
978         double time = PIL_check_seconds_timer();
979         int retval = 0;
980         
981         for (wt = wm->timers.first; wt; wt = wtnext) {
982                 wtnext = wt->next; /* in case timer gets removed */
983                 win = wt->win;
984
985                 if (wt->sleep == 0) {
986                         if (time > wt->ntime) {
987                                 wt->delta = time - wt->ltime;
988                                 wt->duration += wt->delta;
989                                 wt->ltime = time;
990                                 wt->ntime = wt->stime + wt->timestep * ceil(wt->duration / wt->timestep);
991
992                                 if (wt->event_type == TIMERJOBS)
993                                         wm_jobs_timer(C, wm, wt);
994                                 else if (wt->event_type == TIMERAUTOSAVE)
995                                         wm_autosave_timer(C, wm, wt);
996                                 else if (win) {
997                                         wmEvent event = *(win->eventstate);
998                                         
999                                         event.type = wt->event_type;
1000                                         event.val = 0;
1001                                         event.keymodifier = 0;
1002                                         event.custom = EVT_DATA_TIMER;
1003                                         event.customdata = wt;
1004                                         wm_event_add(win, &event);
1005
1006                                         retval = 1;
1007                                 }
1008                         }
1009                 }
1010         }
1011         return retval;
1012 }
1013
1014 void wm_window_process_events(const bContext *C) 
1015 {
1016         int hasevent = GHOST_ProcessEvents(g_system, 0); /* 0 is no wait */
1017         
1018         if (hasevent)
1019                 GHOST_DispatchEvents(g_system);
1020         
1021         hasevent |= wm_window_timer(C);
1022
1023         /* no event, we sleep 5 milliseconds */
1024         if (hasevent == 0)
1025                 PIL_sleep_ms(5);
1026 }
1027
1028 void wm_window_process_events_nosleep(void) 
1029 {
1030         if (GHOST_ProcessEvents(g_system, 0))
1031                 GHOST_DispatchEvents(g_system);
1032 }
1033
1034 /* exported as handle callback to bke blender.c */
1035 void wm_window_testbreak(void)
1036 {
1037         static double ltime = 0;
1038         double curtime = PIL_check_seconds_timer();
1039         
1040         /* only check for breaks every 50 milliseconds
1041          * if we get called more often.
1042          */
1043         if ((curtime - ltime) > 0.05) {
1044                 int hasevent = GHOST_ProcessEvents(g_system, 0); /* 0 is no wait */
1045                 
1046                 if (hasevent)
1047                         GHOST_DispatchEvents(g_system);
1048                 
1049                 ltime = curtime;
1050         }
1051 }
1052
1053 /* **************** init ********************** */
1054
1055 void wm_ghost_init(bContext *C)
1056 {
1057         if (!g_system) {
1058                 GHOST_EventConsumerHandle consumer = GHOST_CreateEventConsumer(ghost_event_proc, C);
1059                 
1060                 g_system = GHOST_CreateSystem();
1061                 GHOST_AddEventConsumer(g_system, consumer);
1062                 
1063                 if (wm_init_state.native_pixels) {
1064                         GHOST_UseNativePixels();
1065                 }
1066         }
1067 }
1068
1069 void wm_ghost_exit(void)
1070 {
1071         if (g_system)
1072                 GHOST_DisposeSystem(g_system);
1073
1074         g_system = NULL;
1075 }
1076
1077 /* **************** timer ********************** */
1078
1079 /* to (de)activate running timers temporary */
1080 void WM_event_timer_sleep(wmWindowManager *wm, wmWindow *UNUSED(win), wmTimer *timer, int dosleep)
1081 {
1082         wmTimer *wt;
1083         
1084         for (wt = wm->timers.first; wt; wt = wt->next)
1085                 if (wt == timer)
1086                         break;
1087
1088         if (wt)
1089                 wt->sleep = dosleep;
1090 }
1091
1092 wmTimer *WM_event_add_timer(wmWindowManager *wm, wmWindow *win, int event_type, double timestep)
1093 {
1094         wmTimer *wt = MEM_callocN(sizeof(wmTimer), "window timer");
1095         
1096         wt->event_type = event_type;
1097         wt->ltime = PIL_check_seconds_timer();
1098         wt->ntime = wt->ltime + timestep;
1099         wt->stime = wt->ltime;
1100         wt->timestep = timestep;
1101         wt->win = win;
1102         
1103         BLI_addtail(&wm->timers, wt);
1104         
1105         return wt;
1106 }
1107
1108 void WM_event_remove_timer(wmWindowManager *wm, wmWindow *UNUSED(win), wmTimer *timer)
1109 {
1110         wmTimer *wt;
1111         
1112         /* extra security check */
1113         for (wt = wm->timers.first; wt; wt = wt->next)
1114                 if (wt == timer)
1115                         break;
1116         if (wt) {
1117                 wmWindow *win;
1118                 
1119                 if (wm->reports.reporttimer == wt)
1120                         wm->reports.reporttimer = NULL;
1121                 
1122                 BLI_remlink(&wm->timers, wt);
1123                 if (wt->customdata)
1124                         MEM_freeN(wt->customdata);
1125                 MEM_freeN(wt);
1126                 
1127                 /* there might be events in queue with this timer as customdata */
1128                 for (win = wm->windows.first; win; win = win->next) {
1129                         wmEvent *event;
1130                         for (event = win->queue.first; event; event = event->next) {
1131                                 if (event->customdata == wt) {
1132                                         //event->customdata = NULL;
1133                                 }
1134                         }
1135                 }
1136         }
1137 }
1138
1139 /* ******************* clipboard **************** */
1140
1141 char *WM_clipboard_text_get(int selection)
1142 {
1143         char *p, *p2, *buf, *newbuf;
1144
1145         if (G.background)
1146                 return NULL;
1147
1148         buf = (char *)GHOST_getClipboard(selection);
1149         if (!buf)
1150                 return NULL;
1151         
1152         /* always convert from \r\n to \n */
1153         newbuf = MEM_callocN(strlen(buf) + 1, __func__);
1154
1155         for (p = buf, p2 = newbuf; *p; p++) {
1156                 if (*p != '\r')
1157                         *(p2++) = *p;
1158         }
1159         *p2 = '\0';
1160
1161         free(buf); /* ghost uses regular malloc */
1162         
1163         return newbuf;
1164 }
1165
1166 void WM_clipboard_text_set(char *buf, int selection)
1167 {
1168         if (!G.background) {
1169 #ifdef _WIN32
1170                 /* do conversion from \n to \r\n on Windows */
1171                 char *p, *p2, *newbuf;
1172                 int newlen = 0;
1173                 
1174                 for (p = buf; *p; p++) {
1175                         if (*p == '\n')
1176                                 newlen += 2;
1177                         else
1178                                 newlen++;
1179                 }
1180                 
1181                 newbuf = MEM_callocN(newlen + 1, "WM_clipboard_text_set");
1182         
1183                 for (p = buf, p2 = newbuf; *p; p++, p2++) {
1184                         if (*p == '\n') {
1185                                 *(p2++) = '\r'; *p2 = '\n';
1186                         }
1187                         else *p2 = *p;
1188                 }
1189                 *p2 = '\0';
1190         
1191                 GHOST_putClipboard((GHOST_TInt8 *)newbuf, selection);
1192                 MEM_freeN(newbuf);
1193 #else
1194                 GHOST_putClipboard((GHOST_TInt8 *)buf, selection);
1195 #endif
1196         }
1197 }
1198
1199 /* ******************* progress bar **************** */
1200
1201 void WM_progress_set(wmWindow *win, float progress)
1202 {
1203         GHOST_SetProgressBar(win->ghostwin, progress);
1204 }
1205
1206 void WM_progress_clear(wmWindow *win)
1207 {
1208         GHOST_EndProgressBar(win->ghostwin);
1209 }
1210
1211 /* ************************************ */
1212
1213 void wm_window_get_position(wmWindow *win, int *posx_r, int *posy_r) 
1214 {
1215         *posx_r = win->posx;
1216         *posy_r = win->posy;
1217 }
1218
1219 void wm_window_set_size(wmWindow *win, int width, int height) 
1220 {
1221         GHOST_SetClientSize(win->ghostwin, width, height);
1222 }
1223
1224 void wm_window_lower(wmWindow *win) 
1225 {
1226         GHOST_SetWindowOrder(win->ghostwin, GHOST_kWindowOrderBottom);
1227 }
1228
1229 void wm_window_raise(wmWindow *win) 
1230 {
1231         GHOST_SetWindowOrder(win->ghostwin, GHOST_kWindowOrderTop);
1232 }
1233
1234 void wm_window_swap_buffers(wmWindow *win)
1235 {
1236         
1237 #ifdef WIN32
1238         glDisable(GL_SCISSOR_TEST);
1239         GHOST_SwapWindowBuffers(win->ghostwin);
1240         glEnable(GL_SCISSOR_TEST);
1241 #else
1242         GHOST_SwapWindowBuffers(win->ghostwin);
1243 #endif
1244 }
1245
1246
1247 /* ******************* exported api ***************** */
1248
1249
1250 /* called whem no ghost system was initialized */
1251 void WM_init_state_size_set(int stax, int stay, int sizx, int sizy)
1252 {
1253         wm_init_state.start_x = stax; /* left hand pos */
1254         wm_init_state.start_y = stay; /* bottom pos */
1255         wm_init_state.size_x = sizx < 640 ? 640 : sizx;
1256         wm_init_state.size_y = sizy < 480 ? 480 : sizy;
1257         wm_init_state.override_flag |= WIN_OVERRIDE_GEOM;
1258 }
1259
1260 /* for borderless and border windows set from command-line */
1261 void WM_init_state_fullscreen_set(void)
1262 {
1263         wm_init_state.windowstate = GHOST_kWindowStateFullScreen;
1264         wm_init_state.override_flag |= WIN_OVERRIDE_WINSTATE;
1265 }
1266
1267 void WM_init_state_normal_set(void)
1268 {
1269         wm_init_state.windowstate = GHOST_kWindowStateNormal;
1270         wm_init_state.override_flag |= WIN_OVERRIDE_WINSTATE;
1271 }
1272
1273 void WM_init_native_pixels(int do_it)
1274 {
1275         wm_init_state.native_pixels = do_it;
1276 }
1277
1278 /* This function requires access to the GHOST_SystemHandle (g_system) */
1279 void WM_cursor_warp(wmWindow *win, int x, int y)
1280 {
1281         if (win && win->ghostwin) {
1282                 float f = GHOST_GetNativePixelSize();
1283                 int oldx = x, oldy = y;
1284
1285                 x = x / f;
1286                 y = y / f;
1287                 y = win->sizey - y - 1;
1288
1289                 GHOST_ClientToScreen(win->ghostwin, x, y, &x, &y);
1290                 GHOST_SetCursorPosition(g_system, x, y);
1291
1292                 win->eventstate->prevx = oldx;
1293                 win->eventstate->prevy = oldy;
1294         }
1295 }
1296
1297 /* support for native pixel size */
1298 /* mac retina opens window in size X, but it has up to 2 x more pixels */
1299 int WM_window_pixels_x(wmWindow *win)
1300 {
1301         float f = GHOST_GetNativePixelSize();
1302         
1303         return (int)(f * (float)win->sizex);
1304 }
1305
1306 int WM_window_pixels_y(wmWindow *win)
1307 {
1308         float f = GHOST_GetNativePixelSize();
1309         
1310         return (int)(f * (float)win->sizey);
1311         
1312 }