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