fix for building windows/mingw
[blender-staging.git] / intern / ghost / intern / GHOST_SystemWin32.cpp
1 /*
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file ghost/intern/GHOST_SystemWin32.cpp
30  *  \ingroup GHOST
31  */
32
33
34 /**
35
36  * $Id$
37  * Copyright (C) 2001 NaN Technologies B.V.
38  * @author      Maarten Gribnau
39  * @date        May 7, 2001
40  */
41
42 #include <iostream>
43
44 #ifdef FREE_WINDOWS
45 #  define _WIN32_WINNT 0x0500 /* GetConsoleWindow() for MinGW */
46 #endif
47
48 #include "GHOST_SystemWin32.h"
49 #include "GHOST_EventDragnDrop.h"
50
51 #define WIN32_LEAN_AND_MEAN
52 #ifdef _WIN32_IE
53 #undef _WIN32_IE
54 #endif
55 #define _WIN32_IE 0x0501
56 #include <windows.h>
57 #include <shlobj.h>
58
59 // win64 doesn't define GWL_USERDATA
60 #ifdef WIN32
61 #ifndef GWL_USERDATA
62 #define GWL_USERDATA GWLP_USERDATA
63 #define GWL_WNDPROC GWLP_WNDPROC 
64 #endif
65 #endif
66
67 /*
68  * According to the docs the mouse wheel message is supported from windows 98 
69  * upwards. Leaving WINVER at default value, the WM_MOUSEWHEEL message and the 
70  * wheel detent value are undefined.
71  */
72 #ifndef WM_MOUSEWHEEL
73 #define WM_MOUSEWHEEL 0x020A
74 #endif // WM_MOUSEWHEEL
75 #ifndef WHEEL_DELTA
76 #define WHEEL_DELTA 120 /* Value for rolling one detent, (old convention! MS changed it) */
77 #endif // WHEEL_DELTA
78
79 /* 
80  * Defines for mouse buttons 4 and 5 aka xbutton1 and xbutton2.
81  * MSDN: Declared in Winuser.h, include Windows.h 
82  * This does not seem to work with MinGW so we define our own here.
83  */
84 #ifndef XBUTTON1
85 #define XBUTTON1 0x0001
86 #endif // XBUTTON1
87 #ifndef XBUTTON2
88 #define XBUTTON2 0x0002
89 #endif // XBUTTON2
90 #ifndef WM_XBUTTONUP
91 #define WM_XBUTTONUP 524
92 #endif // WM_XBUTTONUP
93 #ifndef WM_XBUTTONDOWN
94 #define WM_XBUTTONDOWN 523
95 #endif // WM_XBUTTONDOWN
96
97 #include "GHOST_Debug.h"
98 #include "GHOST_DisplayManagerWin32.h"
99 #include "GHOST_EventButton.h"
100 #include "GHOST_EventCursor.h"
101 #include "GHOST_EventKey.h"
102 #include "GHOST_EventWheel.h"
103 #include "GHOST_EventNDOF.h"
104 #include "GHOST_TimerTask.h"
105 #include "GHOST_TimerManager.h"
106 #include "GHOST_WindowManager.h"
107 #include "GHOST_WindowWin32.h"
108 #include "GHOST_NDOFManager.h"
109
110 // Key code values not found in winuser.h
111 #ifndef VK_MINUS
112 #define VK_MINUS 0xBD
113 #endif // VK_MINUS
114 #ifndef VK_SEMICOLON
115 #define VK_SEMICOLON 0xBA
116 #endif // VK_SEMICOLON
117 #ifndef VK_PERIOD
118 #define VK_PERIOD 0xBE
119 #endif // VK_PERIOD
120 #ifndef VK_COMMA
121 #define VK_COMMA 0xBC
122 #endif // VK_COMMA
123 #ifndef VK_QUOTE
124 #define VK_QUOTE 0xDE
125 #endif // VK_QUOTE
126 #ifndef VK_BACK_QUOTE
127 #define VK_BACK_QUOTE 0xC0
128 #endif // VK_BACK_QUOTE
129 #ifndef VK_SLASH
130 #define VK_SLASH 0xBF
131 #endif // VK_SLASH
132 #ifndef VK_BACK_SLASH
133 #define VK_BACK_SLASH 0xDC
134 #endif // VK_BACK_SLASH
135 #ifndef VK_EQUALS
136 #define VK_EQUALS 0xBB
137 #endif // VK_EQUALS
138 #ifndef VK_OPEN_BRACKET
139 #define VK_OPEN_BRACKET 0xDB
140 #endif // VK_OPEN_BRACKET
141 #ifndef VK_CLOSE_BRACKET
142 #define VK_CLOSE_BRACKET 0xDD
143 #endif // VK_CLOSE_BRACKET
144 #ifndef VK_GR_LESS
145 #define VK_GR_LESS 0xE2
146 #endif // VK_GR_LESS
147
148 #ifndef VK_MEDIA_NEXT_TRACK
149 #define VK_MEDIA_NEXT_TRACK     0xB0
150 #endif // VK_MEDIA_NEXT_TRACK
151 #ifndef VK_MEDIA_PREV_TRACK
152 #define VK_MEDIA_PREV_TRACK     0xB1
153 #endif // VK_MEDIA_PREV_TRACK
154 #ifndef VK_MEDIA_STOP
155 #define VK_MEDIA_STOP   0xB2
156 #endif // VK_MEDIA_STOP
157 #ifndef VK_MEDIA_PLAY_PAUSE
158 #define VK_MEDIA_PLAY_PAUSE     0xB3
159 #endif // VK_MEDIA_PLAY_PAUSE
160
161 /*
162         Initiates WM_INPUT messages from keyboard
163         That way GHOST can retrieve true keys
164 */
165 GHOST_TInt32 GHOST_SystemWin32::initKeyboardRawInput(void)
166 {
167         RAWINPUTDEVICE device = {0};
168         device.usUsagePage      = 0x01; /* usUsagePage & usUsage for keyboard*/
169         device.usUsage          = 0x06; /* http://msdn.microsoft.com/en-us/windows/hardware/gg487473.aspx */
170
171         return RegisterRawInputDevices(&device, 1, sizeof(device));
172 };
173
174 GHOST_SystemWin32::GHOST_SystemWin32()
175 : m_hasPerformanceCounter(false), m_freq(0), m_start(0)
176 {
177         m_displayManager = new GHOST_DisplayManagerWin32 ();
178         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::GHOST_SystemWin32(): m_displayManager==0\n");
179         m_displayManager->initialize();
180
181         m_consoleStatus = 1;
182
183         // Check if current keyboard layout uses AltGr and save keylayout ID for
184         // specialized handling if keys like VK_OEM_*. I.e. french keylayout
185         // generates VK_OEM_8 for their exclamation key (key left of right shift)
186         this->handleKeyboardChange();
187         // Require COM for GHOST_DropTargetWin32 created in GHOST_WindowWin32.
188         OleInitialize(0);
189 }
190
191 GHOST_SystemWin32::~GHOST_SystemWin32()
192 {
193         // Shutdown COM
194         OleUninitialize();
195         toggleConsole(1);
196 }
197
198
199 GHOST_TUns64 GHOST_SystemWin32::getMilliSeconds() const
200 {
201         // Hardware does not support high resolution timers. We will use GetTickCount instead then.
202         if (!m_hasPerformanceCounter) {
203                 return ::GetTickCount();
204         }
205
206         // Retrieve current count
207         __int64 count = 0;
208         ::QueryPerformanceCounter((LARGE_INTEGER*)&count);
209
210         // Calculate the time passed since system initialization.
211         __int64 delta = 1000*(count-m_start);
212
213         GHOST_TUns64 t = (GHOST_TUns64)(delta/m_freq);
214         return t; 
215 }
216
217
218 GHOST_TUns8 GHOST_SystemWin32::getNumDisplays() const
219 {
220         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::getNumDisplays(): m_displayManager==0\n");
221         GHOST_TUns8 numDisplays;
222         m_displayManager->getNumDisplays(numDisplays);
223         return numDisplays;
224 }
225
226
227 void GHOST_SystemWin32::getMainDisplayDimensions(GHOST_TUns32& width, GHOST_TUns32& height) const
228 {
229         width = ::GetSystemMetrics(SM_CXSCREEN);
230         height= ::GetSystemMetrics(SM_CYSCREEN);
231 }
232
233
234 GHOST_IWindow* GHOST_SystemWin32::createWindow(
235         const STR_String& title, 
236         GHOST_TInt32 left, GHOST_TInt32 top, GHOST_TUns32 width, GHOST_TUns32 height,
237         GHOST_TWindowState state, GHOST_TDrawingContextType type,
238         bool stereoVisual, const GHOST_TUns16 numOfAASamples, const GHOST_TEmbedderWindowID parentWindow )
239 {
240         GHOST_Window* window = 0;
241         window = new GHOST_WindowWin32 (this, title, left, top, width, height, state, type, stereoVisual, numOfAASamples);
242         if (window) {
243                 if (window->getValid()) {
244                         // Store the pointer to the window
245 //                      if (state != GHOST_kWindowStateFullScreen) {
246                                 m_windowManager->addWindow(window);
247 //                      }
248                 }
249                 else {
250                         // An invalid window could be one that was used to test for AA
251                         window = ((GHOST_WindowWin32*)window)->getNextWindow();
252                         
253                         // If another window is found, let the wm know about that one, but not the old one
254                         if (window->getValid()) {
255                                 m_windowManager->addWindow(window);
256                         }
257                         else {
258                                 delete window;
259                                 window = 0;
260                         }
261
262                 }
263         }
264         return window;
265 }
266
267
268 bool GHOST_SystemWin32::processEvents(bool waitForEvent)
269 {
270         MSG msg;
271         bool anyProcessed = false;
272
273         do {
274                 GHOST_TimerManager* timerMgr = getTimerManager();
275
276                 if (waitForEvent && !::PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE)) {
277 #if 1
278                         ::Sleep(1);
279 #else
280                         GHOST_TUns64 next = timerMgr->nextFireTime();
281                         GHOST_TInt64 maxSleep = next - getMilliSeconds();
282                         
283                         if (next == GHOST_kFireTimeNever) {
284                                 ::WaitMessage();
285                         } else if(maxSleep >= 0.0) {
286                                 ::SetTimer(NULL, 0, maxSleep, NULL);
287                                 ::WaitMessage();
288                                 ::KillTimer(NULL, 0);
289                         }
290 #endif
291                 }
292
293                 if (timerMgr->fireTimers(getMilliSeconds())) {
294                         anyProcessed = true;
295                 }
296
297                 // Process all the events waiting for us
298                 while (::PeekMessage(&msg, 0, 0, 0, PM_REMOVE) != 0) {
299                         ::TranslateMessage(&msg);
300                         ::DispatchMessage(&msg);
301                         anyProcessed = true;
302                 }
303         } while (waitForEvent && !anyProcessed);
304
305         return anyProcessed;
306 }
307
308
309 GHOST_TSuccess GHOST_SystemWin32::getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const
310 {
311         POINT point;
312         if(::GetCursorPos(&point)){
313                 x = point.x;
314                 y = point.y;
315                 return GHOST_kSuccess;
316         }
317         return GHOST_kFailure;
318 }
319
320
321 GHOST_TSuccess GHOST_SystemWin32::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y)
322 {
323         if (!GetActiveWindow())
324                 return GHOST_kFailure;
325         return ::SetCursorPos(x, y) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
326 }
327
328
329 GHOST_TSuccess GHOST_SystemWin32::getModifierKeys(GHOST_ModifierKeys& keys) const
330 {
331         bool down = HIBYTE(::GetKeyState(VK_LSHIFT)) != 0;
332         keys.set(GHOST_kModifierKeyLeftShift, down);
333         down = HIBYTE(::GetKeyState(VK_RSHIFT)) != 0;
334         keys.set(GHOST_kModifierKeyRightShift, down);
335         
336         down = HIBYTE(::GetKeyState(VK_LMENU)) != 0;
337         keys.set(GHOST_kModifierKeyLeftAlt, down);
338         down = HIBYTE(::GetKeyState(VK_RMENU)) != 0;
339         keys.set(GHOST_kModifierKeyRightAlt, down);
340         
341         down = HIBYTE(::GetKeyState(VK_LCONTROL)) != 0;
342         keys.set(GHOST_kModifierKeyLeftControl, down);
343         down = HIBYTE(::GetKeyState(VK_RCONTROL)) != 0;
344         keys.set(GHOST_kModifierKeyRightControl, down);
345         
346         bool lwindown = HIBYTE(::GetKeyState(VK_LWIN)) != 0;
347         bool rwindown = HIBYTE(::GetKeyState(VK_RWIN)) != 0;
348         if(lwindown || rwindown)
349                 keys.set(GHOST_kModifierKeyOS, true);
350         else
351                 keys.set(GHOST_kModifierKeyOS, false);
352         return GHOST_kSuccess;
353 }
354
355
356 GHOST_TSuccess GHOST_SystemWin32::getButtons(GHOST_Buttons& buttons) const
357 {
358         /* Check for swapped buttons (left-handed mouse buttons)
359          * GetAsyncKeyState() will give back the state of the physical mouse buttons.
360          */
361         bool swapped = ::GetSystemMetrics(SM_SWAPBUTTON) == TRUE;
362
363         bool down = HIBYTE(::GetKeyState(VK_LBUTTON)) != 0;
364         buttons.set(swapped ? GHOST_kButtonMaskRight : GHOST_kButtonMaskLeft, down);
365
366         down = HIBYTE(::GetKeyState(VK_MBUTTON)) != 0;
367         buttons.set(GHOST_kButtonMaskMiddle, down);
368
369         down = HIBYTE(::GetKeyState(VK_RBUTTON)) != 0;
370         buttons.set(swapped ? GHOST_kButtonMaskLeft : GHOST_kButtonMaskRight, down);
371         return GHOST_kSuccess;
372 }
373
374
375 GHOST_TSuccess GHOST_SystemWin32::init()
376 {
377         GHOST_TSuccess success = GHOST_System::init();
378         
379         /* Disable scaling on high DPI displays on Vista */
380         user32 = ::LoadLibraryA("user32.dll");
381         typedef BOOL (WINAPI * LPFNSETPROCESSDPIAWARE)();
382         LPFNSETPROCESSDPIAWARE SetProcessDPIAware =
383                 (LPFNSETPROCESSDPIAWARE)GetProcAddress(user32, "SetProcessDPIAware");
384         if (SetProcessDPIAware)
385                 SetProcessDPIAware();
386         #ifdef NEED_RAW_PROC
387                 pRegisterRawInputDevices = (LPFNDLLRRID)GetProcAddress(user32, "RegisterRawInputDevices");
388                 pGetRawInputData = (LPFNDLLGRID)GetProcAddress(user32, "GetRawInputData");
389         #else
390                 FreeLibrary(user32);
391         #endif
392
393         /*      Initiates WM_INPUT messages from keyboard */
394         initKeyboardRawInput();
395
396
397         // Determine whether this system has a high frequency performance counter. */
398         m_hasPerformanceCounter = ::QueryPerformanceFrequency((LARGE_INTEGER*)&m_freq) == TRUE;
399         if (m_hasPerformanceCounter) {
400                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer available\n")
401                 ::QueryPerformanceCounter((LARGE_INTEGER*)&m_start);
402         }
403         else {
404                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer not available\n")
405         }
406
407         if (success) {
408                 WNDCLASS wc;
409                 wc.style= CS_HREDRAW | CS_VREDRAW;
410                 wc.lpfnWndProc= s_wndProc;
411                 wc.cbClsExtra= 0;
412                 wc.cbWndExtra= 0;
413                 wc.hInstance= ::GetModuleHandle(0);
414                 wc.hIcon = ::LoadIcon(wc.hInstance, "APPICON");
415                 
416                 if (!wc.hIcon) {
417                         ::LoadIcon(NULL, IDI_APPLICATION);
418                 }
419                 wc.hCursor = ::LoadCursor(0, IDC_ARROW);
420                 wc.hbrBackground= (HBRUSH)::GetStockObject(BLACK_BRUSH);
421                 wc.lpszMenuName = 0;
422                 wc.lpszClassName= GHOST_WindowWin32::getWindowClassName();
423
424                 // Use RegisterClassEx for setting small icon
425                 if (::RegisterClass(&wc) == 0) {
426                         success = GHOST_kFailure;
427                 }
428         }
429         
430         return success;
431 }
432
433
434 GHOST_TSuccess GHOST_SystemWin32::exit()
435 {
436         #ifdef NEED_RAW_PROC
437         FreeLibrary(user32);
438         #endif
439
440         return GHOST_System::exit();
441 }
442
443 GHOST_TKey GHOST_SystemWin32::hardKey(GHOST_IWindow *window, WPARAM wParam, LPARAM lParam, int * keyDown, char * vk)
444 {
445         unsigned int size = 0;
446         char * data;
447         GHOST_TKey key = GHOST_kKeyUnknown;
448
449
450         if(!keyDown)
451                 return GHOST_kKeyUnknown;
452
453         GetRawInputData((HRAWINPUT)lParam, RID_INPUT, 0, &size, sizeof(RAWINPUTHEADER));
454
455
456         if((data = (char*)malloc(size)) &&
457                 GetRawInputData((HRAWINPUT)lParam, RID_INPUT, data, &size, sizeof(RAWINPUTHEADER)))
458         {
459                 RAWINPUT ri;
460                 memcpy(&ri,data,(size < sizeof(ri)) ? size : sizeof(ri));
461
462                 if (ri.header.dwType == RIM_TYPEKEYBOARD)
463                 {
464                         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
465                         
466                         GHOST_ModifierKeys modifiers;
467                         system->retrieveModifierKeys(modifiers);
468                         
469                         *keyDown = !(ri.data.keyboard.Flags & RI_KEY_BREAK);
470                         key = this->convertKey(window, ri.data.keyboard.VKey, ri.data.keyboard.MakeCode, (ri.data.keyboard.Flags&(RI_KEY_E1|RI_KEY_E0)));
471                         
472                         // extra handling of modifier keys: don't send repeats out from GHOST
473                         if(key >= GHOST_kKeyLeftShift && key <= GHOST_kKeyRightAlt)
474                         {
475                                 bool changed = false;
476                                 GHOST_TModifierKeyMask modifier;
477                                 switch(key) {
478                                         case GHOST_kKeyLeftShift:
479                                                 {
480                                                         changed = (modifiers.get(GHOST_kModifierKeyLeftShift) != (bool)*keyDown);
481                                                         modifier = GHOST_kModifierKeyLeftShift;
482                                                 }
483                                                 break;
484                                         case GHOST_kKeyRightShift:
485                                                 {
486                                                         changed = (modifiers.get(GHOST_kModifierKeyRightShift) != (bool)*keyDown);
487                                                         modifier = GHOST_kModifierKeyRightShift;
488                                                 }
489                                                 break;
490                                         case GHOST_kKeyLeftControl:
491                                                 {
492                                                         changed = (modifiers.get(GHOST_kModifierKeyLeftControl) != (bool)*keyDown);
493                                                         modifier = GHOST_kModifierKeyLeftControl;
494                                                 }
495                                                 break;
496                                         case GHOST_kKeyRightControl:
497                                                 {
498                                                         changed = (modifiers.get(GHOST_kModifierKeyRightControl) != (bool)*keyDown);
499                                                         modifier = GHOST_kModifierKeyRightControl;
500                                                 }
501                                                 break;
502                                         case GHOST_kKeyLeftAlt:
503                                                 {
504                                                         changed = (modifiers.get(GHOST_kModifierKeyLeftAlt) != (bool)*keyDown);
505                                                         modifier = GHOST_kModifierKeyLeftAlt;
506                                                 }
507                                                 break;
508                                         case GHOST_kKeyRightAlt:
509                                                 {
510                                                         changed = (modifiers.get(GHOST_kModifierKeyRightAlt) != (bool)*keyDown);
511                                                         modifier = GHOST_kModifierKeyRightAlt;
512                                                 }
513                                                 break;
514                                         default: break;
515                                 }
516                                 
517                                 if(changed)
518                                 {
519                                         modifiers.set(modifier, (bool)*keyDown);
520                                         system->storeModifierKeys(modifiers);
521                                 }
522                                 else
523                                 {
524                                         key = GHOST_kKeyUnknown;
525                                 }
526                         }
527                         
528         
529                         if(vk) *vk = ri.data.keyboard.VKey;
530                 };
531
532         };
533         free(data);
534
535         return key;
536 }
537
538 //! note: this function can be extended to include other exotic cases as they arise.
539 // This function was added in response to bug [#25715]
540 GHOST_TKey GHOST_SystemWin32::processSpecialKey(GHOST_IWindow *window, short vKey, short scanCode) const
541 {
542         GHOST_TKey key = GHOST_kKeyUnknown;
543         switch(PRIMARYLANGID(m_langId)) {
544                 case LANG_FRENCH:
545                         if(vKey==VK_OEM_8) key = GHOST_kKeyF13; // oem key; used purely for shortcuts .
546                         break;
547         }
548
549         return key;
550 }
551
552 GHOST_TKey GHOST_SystemWin32::convertKey(GHOST_IWindow *window, short vKey, short scanCode, short extend) const
553 {
554         GHOST_TKey key;
555
556         if ((vKey >= '0') && (vKey <= '9')) {
557                 // VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
558                 key = (GHOST_TKey)(vKey - '0' + GHOST_kKey0);
559         }
560         else if ((vKey >= 'A') && (vKey <= 'Z')) {
561                 // VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
562                 key = (GHOST_TKey)(vKey - 'A' + GHOST_kKeyA);
563         }
564         else if ((vKey >= VK_F1) && (vKey <= VK_F24)) {
565                 key = (GHOST_TKey)(vKey - VK_F1 + GHOST_kKeyF1);
566         }
567         else {
568                 switch (vKey) {
569                 case VK_RETURN:
570                                 key = (extend)?GHOST_kKeyNumpadEnter : GHOST_kKeyEnter; break;
571                         
572                 case VK_BACK:     key = GHOST_kKeyBackSpace;            break;
573                 case VK_TAB:      key = GHOST_kKeyTab;                          break;
574                 case VK_ESCAPE:   key = GHOST_kKeyEsc;                          break;
575                 case VK_SPACE:    key = GHOST_kKeySpace;                        break;
576                 
577                 case VK_INSERT:
578                 case VK_NUMPAD0:
579                         key = (extend) ? GHOST_kKeyInsert : GHOST_kKeyNumpad0;  break;
580                 case VK_END:
581                 case VK_NUMPAD1:        
582                         key = (extend) ? GHOST_kKeyEnd : GHOST_kKeyNumpad1;     break;
583                 case VK_DOWN:
584                 case VK_NUMPAD2:
585                         key = (extend) ? GHOST_kKeyDownArrow : GHOST_kKeyNumpad2;       break;
586                 case VK_NEXT:
587                 case VK_NUMPAD3:
588                         key = (extend) ?  GHOST_kKeyDownPage : GHOST_kKeyNumpad3;       break;
589                 case VK_LEFT:
590                 case VK_NUMPAD4:
591                         key = (extend) ? GHOST_kKeyLeftArrow : GHOST_kKeyNumpad4;       break;
592                 case VK_CLEAR:
593                 case VK_NUMPAD5:
594                         key = (extend) ? GHOST_kKeyUnknown: GHOST_kKeyNumpad5;  break;
595                 case VK_RIGHT:
596                 case VK_NUMPAD6:
597                         key = (extend) ? GHOST_kKeyRightArrow : GHOST_kKeyNumpad6;      break;
598                 case VK_HOME:
599                 case VK_NUMPAD7:
600                         key = (extend) ? GHOST_kKeyHome : GHOST_kKeyNumpad7;    break;
601                 case VK_UP:
602                 case VK_NUMPAD8:
603                         key = (extend) ? GHOST_kKeyUpArrow : GHOST_kKeyNumpad8; break;
604                 case VK_PRIOR:
605                 case VK_NUMPAD9:
606                         key = (extend) ? GHOST_kKeyUpPage : GHOST_kKeyNumpad9;  break;
607                 case VK_DECIMAL:
608                 case VK_DELETE:
609                         key = (extend) ? GHOST_kKeyDelete : GHOST_kKeyNumpadPeriod;     break;
610
611                 case VK_SNAPSHOT: key = GHOST_kKeyPrintScreen;          break;
612                 case VK_PAUSE:    key = GHOST_kKeyPause;                        break;
613                 case VK_MULTIPLY: key = GHOST_kKeyNumpadAsterisk;       break;
614                 case VK_SUBTRACT: key = GHOST_kKeyNumpadMinus;          break;
615                 case VK_DIVIDE:   key = GHOST_kKeyNumpadSlash;          break;
616                 case VK_ADD:      key = GHOST_kKeyNumpadPlus;           break;
617
618                 case VK_SEMICOLON:              key = GHOST_kKeySemicolon;              break;
619                 case VK_EQUALS:                 key = GHOST_kKeyEqual;                  break;
620                 case VK_COMMA:                  key = GHOST_kKeyComma;                  break;
621                 case VK_MINUS:                  key = GHOST_kKeyMinus;                  break;
622                 case VK_PERIOD:                 key = GHOST_kKeyPeriod;                 break;
623                 case VK_SLASH:                  key = GHOST_kKeySlash;                  break;
624                 case VK_BACK_QUOTE:             key = GHOST_kKeyAccentGrave;    break;
625                 case VK_OPEN_BRACKET:   key = GHOST_kKeyLeftBracket;    break;
626                 case VK_BACK_SLASH:             key = GHOST_kKeyBackslash;              break;
627                 case VK_CLOSE_BRACKET:  key = GHOST_kKeyRightBracket;   break;
628                 case VK_QUOTE:                  key = GHOST_kKeyQuote;                  break;
629                 case VK_GR_LESS:                key = GHOST_kKeyGrLess;                 break;
630
631                 case VK_SHIFT:
632                         key = (scanCode == 0x36)? GHOST_kKeyRightShift : GHOST_kKeyLeftShift;
633                         break;
634                 case VK_CONTROL:
635                         key = (extend)? GHOST_kKeyRightControl : GHOST_kKeyLeftControl;
636                         break;
637                 case VK_MENU:
638                         key = (extend)? GHOST_kKeyRightAlt : GHOST_kKeyLeftAlt;
639                         break;
640                 case VK_LWIN:
641                 case VK_RWIN:
642                         key = GHOST_kKeyOS;
643                         break;
644                 case VK_NUMLOCK: key = GHOST_kKeyNumLock; break;
645                 case VK_SCROLL: key = GHOST_kKeyScrollLock; break;
646                 case VK_CAPITAL: key = GHOST_kKeyCapsLock; break;
647                 case VK_OEM_8:
648                         key = ((GHOST_SystemWin32*)getSystem())->processSpecialKey(window, vKey, scanCode);
649                         break;
650                 case VK_MEDIA_PLAY_PAUSE: key = GHOST_kKeyMediaPlay; break;
651                 case VK_MEDIA_STOP: key = GHOST_kKeyMediaStop; break;
652                 case VK_MEDIA_PREV_TRACK: key = GHOST_kKeyMediaFirst; break;
653                 case VK_MEDIA_NEXT_TRACK: key = GHOST_kKeyMediaLast; break;
654                 default:
655                         key = GHOST_kKeyUnknown;
656                         break;
657                 }
658         }
659         
660         return key;
661 }
662
663 GHOST_EventButton* GHOST_SystemWin32::processButtonEvent(GHOST_TEventType type, GHOST_IWindow *window, GHOST_TButtonMask mask)
664 {
665         return new GHOST_EventButton (getSystem()->getMilliSeconds(), type, window, mask);
666 }
667
668
669 GHOST_EventCursor* GHOST_SystemWin32::processCursorEvent(GHOST_TEventType type, GHOST_IWindow *Iwindow)
670 {
671         GHOST_TInt32 x_screen, y_screen;
672         GHOST_SystemWin32 * system = ((GHOST_SystemWin32 * ) getSystem());
673         GHOST_WindowWin32 * window = ( GHOST_WindowWin32 * ) Iwindow;
674         
675         system->getCursorPosition(x_screen, y_screen);
676
677         if(window->getCursorGrabMode() != GHOST_kGrabDisable && window->getCursorGrabMode() != GHOST_kGrabNormal)
678         {
679                 GHOST_TInt32 x_new= x_screen;
680                 GHOST_TInt32 y_new= y_screen;
681                 GHOST_TInt32 x_accum, y_accum;
682                 GHOST_Rect bounds;
683
684                 /* fallback to window bounds */
685                 if(window->getCursorGrabBounds(bounds)==GHOST_kFailure){
686                         window->getClientBounds(bounds);
687                 }
688
689                 /* could also clamp to screen bounds
690                  * wrap with a window outside the view will fail atm  */
691
692                 bounds.wrapPoint(x_new, y_new, 2); /* offset of one incase blender is at screen bounds */
693
694                 window->getCursorGrabAccum(x_accum, y_accum);
695                 if(x_new != x_screen|| y_new != y_screen) {
696                         /* when wrapping we don't need to add an event because the
697                          * setCursorPosition call will cause a new event after */
698                         system->setCursorPosition(x_new, y_new); /* wrap */
699                         window->setCursorGrabAccum(x_accum + (x_screen - x_new), y_accum + (y_screen - y_new));
700                 }else{
701                         return new GHOST_EventCursor(system->getMilliSeconds(),
702                                                                                  GHOST_kEventCursorMove,
703                                                                                  window,
704                                                                                  x_screen + x_accum,
705                                                                                  y_screen + y_accum
706                         );
707                 }
708
709         }
710         else {
711                 return new GHOST_EventCursor(system->getMilliSeconds(),
712                                                                          GHOST_kEventCursorMove,
713                                                                          window,
714                                                                          x_screen,
715                                                                          y_screen
716                 );
717         }
718         return NULL;
719 }
720
721
722 GHOST_EventWheel* GHOST_SystemWin32::processWheelEvent(GHOST_IWindow *window, WPARAM wParam, LPARAM lParam)
723 {
724         // short fwKeys = LOWORD(wParam);                       // key flags
725         int zDelta = (short) HIWORD(wParam);    // wheel rotation
726         
727         // zDelta /= WHEEL_DELTA;
728         // temporary fix below: microsoft now has added more precision, making the above division not work
729         if (zDelta <= 0 ) zDelta= -1; else zDelta= 1;   
730         
731         // short xPos = (short) LOWORD(lParam); // horizontal position of pointer
732         // short yPos = (short) HIWORD(lParam); // vertical position of pointer
733         return new GHOST_EventWheel (getSystem()->getMilliSeconds(), window, zDelta);
734 }
735
736
737 GHOST_EventKey* GHOST_SystemWin32::processKeyEvent(GHOST_IWindow *window, WPARAM wParam, LPARAM lParam)
738 {
739         int keyDown=0;
740         char vk;
741         GHOST_SystemWin32 * system = (GHOST_SystemWin32 *)getSystem();
742         GHOST_TKey key = system->hardKey(window, wParam, lParam, &keyDown, &vk);
743         GHOST_EventKey* event;
744         if (key != GHOST_kKeyUnknown) {
745                 char ascii = '\0';
746
747                 unsigned short utf16[2]={0};
748                 BYTE state[256];
749                 GetKeyboardState((PBYTE)state);
750
751                 if(ToAsciiEx(vk, 0, state, utf16, 0, system->m_keylayout))
752                                 WideCharToMultiByte(CP_ACP, 0x00000400, 
753                                                                         (wchar_t*)utf16, 1,
754                                                                         (LPSTR) &ascii, 1,
755                                                                         NULL,NULL);
756
757                 event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown: GHOST_kEventKeyUp, window, key, ascii);
758                 
759 #ifdef BF_GHOST_DEBUG
760                 std::cout << ascii << std::endl;
761 #endif
762         }
763         else {
764                 event = 0;
765         }
766         return event;
767 }
768
769
770 GHOST_Event* GHOST_SystemWin32::processWindowEvent(GHOST_TEventType type, GHOST_IWindow* window)
771 {
772         return new GHOST_Event(getSystem()->getMilliSeconds(), type, window);
773 }
774
775 GHOST_TSuccess GHOST_SystemWin32::pushDragDropEvent(GHOST_TEventType eventType, 
776                                                                                                         GHOST_TDragnDropTypes draggedObjectType,
777                                                                                                         GHOST_IWindow* window,
778                                                                                                         int mouseX, int mouseY,
779                                                                                                         void* data)
780 {
781         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
782         return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
783                                                                                                           eventType,
784                                                                                                           draggedObjectType,
785                                                                                                           window,mouseX,mouseY,data)
786                         );
787 }
788
789 void GHOST_SystemWin32::processMinMaxInfo(MINMAXINFO * minmax)
790 {
791         minmax->ptMinTrackSize.x=320;
792         minmax->ptMinTrackSize.y=240;
793 }
794
795 LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
796 {
797         GHOST_Event* event = 0;
798         LRESULT lResult = 0;
799         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
800         GHOST_ASSERT(system, "GHOST_SystemWin32::s_wndProc(): system not initialized")
801
802         if (hwnd) {
803                 GHOST_WindowWin32* window = (GHOST_WindowWin32*)::GetWindowLong(hwnd, GWL_USERDATA);
804                 if (window) {
805                         switch (msg) {
806                                 // we need to check if new key layout has AltGr
807                                 case WM_INPUTLANGCHANGE:
808                                         system->handleKeyboardChange();
809                                         break;
810                                 ////////////////////////////////////////////////////////////////////////
811                                 // Keyboard events, processed
812                                 ////////////////////////////////////////////////////////////////////////
813                                 case WM_INPUT:
814                                         event = processKeyEvent(window, wParam, lParam);
815                                         if (!event) {
816                                                 GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ")
817                                                 GHOST_PRINT(msg)
818                                                 GHOST_PRINT(" key ignored\n")
819                                         }
820                                         break;
821                                 ////////////////////////////////////////////////////////////////////////
822                                 // Keyboard events, ignored
823                                 ////////////////////////////////////////////////////////////////////////
824                                 case WM_KEYDOWN:
825                                 case WM_SYSKEYDOWN:
826                                 case WM_KEYUP:
827                                 case WM_SYSKEYUP:
828                                         /* These functions were replaced by WM_INPUT*/
829                                 case WM_CHAR:
830                                         /* The WM_CHAR message is posted to the window with the keyboard focus when 
831                                          * a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR 
832                                          * contains the character code of the key that was pressed. 
833                                          */
834                                 case WM_DEADCHAR:
835                                         /* The WM_DEADCHAR message is posted to the window with the keyboard focus when a
836                                          * WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR 
837                                          * specifies a character code generated by a dead key. A dead key is a key that 
838                                          * generates a character, such as the umlaut (double-dot), that is combined with 
839                                          * another character to form a composite character. For example, the umlaut-O 
840                                          * character (Ö) is generated by typing the dead key for the umlaut character, and
841                                          * then typing the O key.
842                                          */
843                                         break;
844                                 case WM_SYSDEADCHAR:
845                                         /* The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when 
846                                          * a WM_SYSKEYDOWN message is translated by the TranslateMessage function. 
847                                          * WM_SYSDEADCHAR specifies the character code of a system dead key - that is, 
848                                          * a dead key that is pressed while holding down the alt key. 
849                                          */
850                                 case WM_SYSCHAR:
851                                         /* The WM_SYSCHAR message is sent to the window with the keyboard focus when 
852                                          * a WM_SYSCHAR message is translated by the TranslateMessage function. 
853                                          * WM_SYSCHAR specifies the character code of a dead key - that is, 
854                                          * a dead key that is pressed while holding down the alt key.
855                                          * To prevent the sound, DefWindowProc must be avoided by return
856                                          */
857                                         break;
858                                 case WM_SYSCOMMAND:
859                                         /* The WM_SYSCHAR message is sent to the window when system commands such as 
860                                          * maximize, minimize  or close the window are triggered. Also it is sent when ALT 
861                                          * button is press for menu. To prevent this we must return preventing DefWindowProc.
862                                          */
863                                         if(wParam==SC_KEYMENU) return 0;
864                                         break;
865                                 ////////////////////////////////////////////////////////////////////////
866                                 // Tablet events, processed
867                                 ////////////////////////////////////////////////////////////////////////
868                                 case WT_PACKET:
869                                         ((GHOST_WindowWin32*)window)->processWin32TabletEvent(wParam, lParam);
870                                         break;
871                                 case WT_CSRCHANGE:
872                                 case WT_PROXIMITY:
873                                         ((GHOST_WindowWin32*)window)->processWin32TabletInitEvent();
874                                         break;
875                                 ////////////////////////////////////////////////////////////////////////
876                                 // Mouse events, processed
877                                 ////////////////////////////////////////////////////////////////////////
878                                 case WM_LBUTTONDOWN:
879                                         window->registerMouseClickEvent(0);
880                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskLeft);
881                                         break;
882                                 case WM_MBUTTONDOWN:
883                                         window->registerMouseClickEvent(0);
884                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskMiddle);
885                                         break;
886                                 case WM_RBUTTONDOWN:
887                                         window->registerMouseClickEvent(0);
888                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskRight);
889                                         break;
890                                 case WM_XBUTTONDOWN:
891                                         window->registerMouseClickEvent(0);
892                                         if ((short) HIWORD(wParam) == XBUTTON1){
893                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton4);
894                                         }else if((short) HIWORD(wParam) == XBUTTON2){
895                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton5);
896                                         }
897                                         break;
898                                 case WM_LBUTTONUP:
899                                         window->registerMouseClickEvent(1);
900                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskLeft);
901                                         break;
902                                 case WM_MBUTTONUP:
903                                         window->registerMouseClickEvent(1);
904                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskMiddle);
905                                         break;
906                                 case WM_RBUTTONUP:
907                                         window->registerMouseClickEvent(1);
908                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskRight);
909                                         break;
910                                 case WM_XBUTTONUP:
911                                         window->registerMouseClickEvent(1);
912                                         if ((short) HIWORD(wParam) == XBUTTON1){
913                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton4);
914                                         }else if((short) HIWORD(wParam) == XBUTTON2){
915                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton5);
916                                         }
917                                         break;
918                                 case WM_MOUSEMOVE:
919                                         event = processCursorEvent(GHOST_kEventCursorMove, window);
920                                         break;
921                                 case WM_MOUSEWHEEL:
922                                         /* The WM_MOUSEWHEEL message is sent to the focus window 
923                                          * when the mouse wheel is rotated. The DefWindowProc 
924                                          * function propagates the message to the window's parent.
925                                          * There should be no internal forwarding of the message, 
926                                          * since DefWindowProc propagates it up the parent chain 
927                                          * until it finds a window that processes it.
928                                          */
929                                         event = processWheelEvent(window, wParam, lParam);
930                                         break;
931                                 case WM_SETCURSOR:
932                                         /* The WM_SETCURSOR message is sent to a window if the mouse causes the cursor
933                                          * to move within a window and mouse input is not captured.
934                                          * This means we have to set the cursor shape every time the mouse moves!
935                                          * The DefWindowProc function uses this message to set the cursor to an 
936                                          * arrow if it is not in the client area.
937                                          */
938                                         if (LOWORD(lParam) == HTCLIENT) {
939                                                 // Load the current cursor
940                                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
941                                                 // Bypass call to DefWindowProc
942                                                 return 0;
943                                         } 
944                                         else {
945                                                 // Outside of client area show standard cursor
946                                                 window->loadCursor(true, GHOST_kStandardCursorDefault);
947                                         }
948                                         break;
949
950                                 ////////////////////////////////////////////////////////////////////////
951                                 // Mouse events, ignored
952                                 ////////////////////////////////////////////////////////////////////////
953                                 case WM_NCMOUSEMOVE:
954                                         /* The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved 
955                                          * within the nonclient area of the window. This message is posted to the window 
956                                          * that contains the cursor. If a window has captured the mouse, this message is not posted.
957                                          */
958                                 case WM_NCHITTEST:
959                                         /* The WM_NCHITTEST message is sent to a window when the cursor moves, or 
960                                          * when a mouse button is pressed or released. If the mouse is not captured, 
961                                          * the message is sent to the window beneath the cursor. Otherwise, the message 
962                                          * is sent to the window that has captured the mouse. 
963                                          */
964                                         break;
965
966                                 ////////////////////////////////////////////////////////////////////////
967                                 // Window events, processed
968                                 ////////////////////////////////////////////////////////////////////////
969                                 case WM_CLOSE:
970                                         /* The WM_CLOSE message is sent as a signal that a window or an application should terminate. */
971                                         event = processWindowEvent(GHOST_kEventWindowClose, window);
972                                         break;
973                                 case WM_ACTIVATE:
974                                         /* The WM_ACTIVATE message is sent to both the window being activated and the window being 
975                                          * deactivated. If the windows use the same input queue, the message is sent synchronously, 
976                                          * first to the window procedure of the top-level window being deactivated, then to the window
977                                          * procedure of the top-level window being activated. If the windows use different input queues,
978                                          * the message is sent asynchronously, so the window is activated immediately. 
979                                          */
980                                         event = processWindowEvent(LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
981                                         /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
982                                         will not be dispatched to OUR active window if we minimize one of OUR windows. */
983                                         lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
984                                         break;
985                                 case WM_PAINT:
986                                         /* An application sends the WM_PAINT message when the system or another application 
987                                          * makes a request to paint a portion of an application's window. The message is sent
988                                          * when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage 
989                                          * function when the application obtains a WM_PAINT message by using the GetMessage or 
990                                          * PeekMessage function. 
991                                          */
992                                         event = processWindowEvent(GHOST_kEventWindowUpdate, window);
993                                         ::ValidateRect(hwnd, NULL);
994                                         break;
995                                 case WM_GETMINMAXINFO:
996                                         /* The WM_GETMINMAXINFO message is sent to a window when the size or 
997                                          * position of the window is about to change. An application can use 
998                                          * this message to override the window's default maximized size and 
999                                          * position, or its default minimum or maximum tracking size. 
1000                                          */
1001                                         processMinMaxInfo((MINMAXINFO *) lParam);
1002                                         /* Let DefWindowProc handle it. */
1003                                         break;
1004                                 case WM_SIZE:
1005                                         /* The WM_SIZE message is sent to a window after its size has changed.
1006                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1007                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1008                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1009                                          * message without calling DefWindowProc.
1010                                          */
1011                                         event = processWindowEvent(GHOST_kEventWindowSize, window);
1012                                         break;
1013                                 case WM_CAPTURECHANGED:
1014                                         window->lostMouseCapture();
1015                                         break;
1016                                 case WM_MOVING:
1017                                         /* The WM_MOVING message is sent to a window that the user is moving. By processing 
1018                                          * this message, an application can monitor the size and position of the drag rectangle
1019                                          * and, if needed, change its size or position.
1020                                          */
1021                                 case WM_MOVE:
1022                                         /* The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1023                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1024                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1025                                          * message without calling DefWindowProc. 
1026                                          */
1027                                         event = processWindowEvent(GHOST_kEventWindowMove, window);
1028                                         break;
1029                                 ////////////////////////////////////////////////////////////////////////
1030                                 // Window events, ignored
1031                                 ////////////////////////////////////////////////////////////////////////
1032                                 case WM_WINDOWPOSCHANGED:
1033                                         /* The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place
1034                                          * in the Z order has changed as a result of a call to the SetWindowPos function or 
1035                                          * another window-management function.
1036                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1037                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1038                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1039                                          * message without calling DefWindowProc.
1040                                          */
1041                                 case WM_ERASEBKGND:
1042                                         /* An application sends the WM_ERASEBKGND message when the window background must be 
1043                                          * erased (for example, when a window is resized). The message is sent to prepare an 
1044                                          * invalidated portion of a window for painting. 
1045                                          */
1046                                 case WM_NCPAINT:
1047                                         /* An application sends the WM_NCPAINT message to a window when its frame must be painted. */
1048                                 case WM_NCACTIVATE:
1049                                         /* The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed 
1050                                          * to indicate an active or inactive state. 
1051                                          */
1052                                 case WM_DESTROY:
1053                                         /* The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window 
1054                                          * procedure of the window being destroyed after the window is removed from the screen. 
1055                                          * This message is sent first to the window being destroyed and then to the child windows 
1056                                          * (if any) as they are destroyed. During the processing of the message, it can be assumed 
1057                                          * that all child windows still exist. 
1058                                          */
1059                                 case WM_NCDESTROY:
1060                                         /* The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The 
1061                                          * DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY
1062                                          * message. WM_DESTROY is used to free the allocated memory object associated with the window. 
1063                                          */
1064                                         break;
1065                                 case WM_KILLFOCUS:
1066                                         /* The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus. 
1067                                          * We want to prevent this if a window is still active and it loses focus to nowhere*/
1068                                         if(!wParam && hwnd==GetActiveWindow())
1069                                                 SetFocus(hwnd);
1070                                 case WM_SHOWWINDOW:
1071                                         /* The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown. */
1072                                 case WM_WINDOWPOSCHANGING:
1073                                         /* The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in 
1074                                          * the Z order is about to change as a result of a call to the SetWindowPos function or 
1075                                          * another window-management function. 
1076                                          */
1077                                 case WM_SETFOCUS:
1078                                         /* The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus. */
1079                                 case WM_ENTERSIZEMOVE:
1080                                         /* The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving 
1081                                          * or sizing modal loop. The window enters the moving or sizing modal loop when the user 
1082                                          * clicks the window's title bar or sizing border, or when the window passes the 
1083                                          * WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the 
1084                                          * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when 
1085                                          * DefWindowProc returns. 
1086                                          */
1087                                         break;
1088                                         
1089                                 ////////////////////////////////////////////////////////////////////////
1090                                 // Other events
1091                                 ////////////////////////////////////////////////////////////////////////
1092                                 case WM_GETTEXT:
1093                                         /* An application sends a WM_GETTEXT message to copy the text that 
1094                                          * corresponds to a window into a buffer provided by the caller. 
1095                                          */
1096                                 case WM_ACTIVATEAPP:
1097                                         /* The WM_ACTIVATEAPP message is sent when a window belonging to a 
1098                                          * different application than the active window is about to be activated.
1099                                          * The message is sent to the application whose window is being activated
1100                                          * and to the application whose window is being deactivated. 
1101                                          */
1102                                 case WM_TIMER:
1103                                         /* The WIN32 docs say:
1104                                          * The WM_TIMER message is posted to the installing thread's message queue
1105                                          * when a timer expires. You can process the message by providing a WM_TIMER
1106                                          * case in the window procedure. Otherwise, the default window procedure will
1107                                          * call the TimerProc callback function specified in the call to the SetTimer
1108                                          * function used to install the timer. 
1109                                          *
1110                                          * In GHOST, we let DefWindowProc call the timer callback.
1111                                          */
1112                                         break;
1113                                 case WM_BLND_NDOF_AXIS:
1114                                         {
1115                                                 GHOST_TEventNDOFData ndofdata;
1116                                                 system->m_ndofManager->GHOST_NDOFGetDatas(ndofdata);
1117                                                 system->m_eventManager->
1118                                                         pushEvent(new GHOST_EventNDOF(
1119                                                                 system->getMilliSeconds(), 
1120                                                                 GHOST_kEventNDOFMotion, 
1121                                                                 window, ndofdata));
1122                                         }
1123                                         break;
1124                                 case WM_BLND_NDOF_BTN:
1125                                         {
1126                                                 GHOST_TEventNDOFData ndofdata;
1127                                                 system->m_ndofManager->GHOST_NDOFGetDatas(ndofdata);
1128                                                 system->m_eventManager->
1129                                                         pushEvent(new GHOST_EventNDOF(
1130                                                                 system->getMilliSeconds(), 
1131                                                                 GHOST_kEventNDOFButton, 
1132                                                                 window, ndofdata));
1133                                         }
1134                                         break;
1135                         }
1136                 }
1137                 else {
1138                         // Event found for a window before the pointer to the class has been set.
1139                         GHOST_PRINT("GHOST_SystemWin32::wndProc: GHOST window event before creation\n")
1140                         /* These are events we typically miss at this point:
1141                            WM_GETMINMAXINFO     0x24
1142                            WM_NCCREATE                  0x81
1143                            WM_NCCALCSIZE                0x83
1144                            WM_CREATE                    0x01
1145                            We let DefWindowProc do the work.
1146                         */
1147                 }
1148         }
1149         else {
1150                 // Events without valid hwnd
1151                 GHOST_PRINT("GHOST_SystemWin32::wndProc: event without window\n")
1152         }
1153
1154         if (event) {
1155                 system->pushEvent(event);
1156         }
1157         else {
1158                 lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
1159         }
1160         return lResult;
1161 }
1162
1163 GHOST_TUns8* GHOST_SystemWin32::getClipboard(bool selection) const 
1164 {
1165         char *buffer;
1166         char *temp_buff;
1167         
1168         if ( IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL) ) {
1169                 HANDLE hData = GetClipboardData( CF_TEXT );
1170                 if (hData == NULL) {
1171                         CloseClipboard();
1172                         return NULL;
1173                 }
1174                 buffer = (char*)GlobalLock( hData );
1175                 
1176                 temp_buff = (char*) malloc(strlen(buffer)+1);
1177                 strcpy(temp_buff, buffer);
1178                 
1179                 GlobalUnlock( hData );
1180                 CloseClipboard();
1181                 
1182                 temp_buff[strlen(buffer)] = '\0';
1183                 if (buffer) {
1184                         return (GHOST_TUns8*)temp_buff;
1185                 } else {
1186                         return NULL;
1187                 }
1188         } else {
1189                 return NULL;
1190         }
1191 }
1192
1193 void GHOST_SystemWin32::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1194 {
1195         if(selection) {return;} // for copying the selection, used on X11
1196
1197         if (OpenClipboard(NULL)) {
1198                 HLOCAL clipbuffer;
1199                 char *data;
1200                 
1201                 if (buffer) {
1202                         EmptyClipboard();
1203                         
1204                         clipbuffer = LocalAlloc(LMEM_FIXED,((strlen(buffer)+1)));
1205                         data = (char*)GlobalLock(clipbuffer);
1206
1207                         strcpy(data, (char*)buffer);
1208                         data[strlen(buffer)] = '\0';
1209                         LocalUnlock(clipbuffer);
1210                         SetClipboardData(CF_TEXT,clipbuffer);
1211                 }
1212                 CloseClipboard();
1213         } else {
1214                 return;
1215         }
1216 }
1217
1218 int GHOST_SystemWin32::toggleConsole(int action)
1219 {
1220         switch(action)
1221         {
1222                 case 3: //hide if no console
1223                         {
1224                         CONSOLE_SCREEN_BUFFER_INFO csbi = {{0}};
1225                         if(!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi) || csbi.dwCursorPosition.X || csbi.dwCursorPosition.Y>1)
1226                                 break;
1227                         }
1228                 case 0: //hide
1229                         ShowWindow(GetConsoleWindow(),SW_HIDE);
1230                         m_consoleStatus = 0;
1231                         break;
1232                 case 1: //show
1233                         ShowWindow(GetConsoleWindow(),SW_SHOW);
1234                         m_consoleStatus = 1;
1235                         break;
1236                 case 2: //toggle
1237                         ShowWindow(GetConsoleWindow(),m_consoleStatus?SW_HIDE:SW_SHOW);
1238                         m_consoleStatus=!m_consoleStatus;
1239                         break;
1240
1241         };
1242
1243
1244         return m_consoleStatus;
1245 }