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