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