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