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