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