Merging r38818 through r39198 from trunk into vgroup_modifiers.
[blender-staging.git] / intern / ghost / intern / GHOST_SystemWin32.cpp
1 /*
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file ghost/intern/GHOST_SystemWin32.cpp
30  *  \ingroup GHOST
31  */
32
33
34 /**
35
36  * $Id$
37  * Copyright (C) 2001 NaN Technologies B.V.
38  * @author      Maarten Gribnau
39  * @date        May 7, 2001
40  */
41
42 #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         if (key != GHOST_kKeyUnknown) {
716                 char ascii = '\0';
717
718                 unsigned short utf16[2]={0};
719                 BYTE state[256];
720                 GetKeyboardState((PBYTE)state);
721
722                 if(ToAsciiEx(vk, 0, state, utf16, 0, system->m_keylayout))
723                                 WideCharToMultiByte(CP_ACP, 0x00000400, 
724                                                                         (wchar_t*)utf16, 1,
725                                                                         (LPSTR) &ascii, 1,
726                                                                         NULL,NULL);
727
728                 event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown: GHOST_kEventKeyUp, window, key, ascii);
729                 
730 #ifdef GHOST_DEBUG
731                 std::cout << ascii << std::endl;
732 #endif
733         }
734         else {
735                 event = 0;
736         }
737         return event;
738 }
739
740
741 GHOST_Event* GHOST_SystemWin32::processWindowEvent(GHOST_TEventType type, GHOST_IWindow* window)
742 {
743         GHOST_System* system = (GHOST_System*)getSystem();
744
745         if (type == GHOST_kEventWindowActivate) {
746                 system->getWindowManager()->setActiveWindow(window);
747         }
748
749         return new GHOST_Event(system->getMilliSeconds(), type, window);
750 }
751
752 GHOST_TSuccess GHOST_SystemWin32::pushDragDropEvent(GHOST_TEventType eventType, 
753                                                                                                         GHOST_TDragnDropTypes draggedObjectType,
754                                                                                                         GHOST_IWindow* window,
755                                                                                                         int mouseX, int mouseY,
756                                                                                                         void* data)
757 {
758         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
759         return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
760                                                                                                           eventType,
761                                                                                                           draggedObjectType,
762                                                                                                           window,mouseX,mouseY,data)
763                         );
764 }
765
766 void GHOST_SystemWin32::processMinMaxInfo(MINMAXINFO * minmax)
767 {
768         minmax->ptMinTrackSize.x=320;
769         minmax->ptMinTrackSize.y=240;
770 }
771
772 #ifdef WITH_INPUT_NDOF
773 bool GHOST_SystemWin32::processNDOF(RAWINPUT const& raw)
774 {
775         bool eventSent = false;
776         GHOST_TUns64 now = getMilliSeconds();
777
778         static bool firstEvent = true;
779         if (firstEvent) { // determine exactly which device is plugged in
780                 RID_DEVICE_INFO info;
781                 unsigned infoSize = sizeof(RID_DEVICE_INFO);
782                 info.cbSize = infoSize;
783
784                 GetRawInputDeviceInfo(raw.header.hDevice, RIDI_DEVICEINFO, &info, &infoSize);
785                 if (info.dwType == RIM_TYPEHID)
786                         m_ndofManager->setDevice(info.hid.dwVendorId, info.hid.dwProductId);
787                 else
788                         puts("<!> not a HID device... mouse/kb perhaps?");
789
790                 firstEvent = false;
791         }
792
793         // The NDOF manager sends button changes immediately, and *pretends* to
794         // send motion. Mark as 'sent' so motion will always get dispatched.
795         eventSent = true;
796
797 #ifdef _MSC_VER
798         // using Microsoft compiler & header files
799         // they invented the RawInput API, so this version is (probably) correct
800         BYTE const* data = raw.data.hid.bRawData;
801         // struct RAWHID {
802         // DWORD dwSizeHid;
803         // DWORD dwCount;
804         // BYTE  bRawData[1];
805         // };
806 #else
807         // MinGW's definition (below) doesn't agree, so we need a slight
808         // workaround until it's fixed
809         BYTE const* data = &raw.data.hid.bRawData;
810         // struct RAWHID {
811         // DWORD dwSizeHid;
812         // DWORD dwCount;
813         // BYTE bRawData; // <== isn't this s'posed to be a BYTE*?
814         // };
815 #endif
816
817         BYTE packetType = data[0];
818         switch (packetType)
819         {
820                 case 1: // translation
821                 {
822                         short* axis = (short*)(data + 1);
823                         // massage into blender view coords (same goes for rotation)
824                         short t[3] = {axis[0], -axis[2], axis[1]};
825                         m_ndofManager->updateTranslation(t, now);
826
827                         if (raw.data.hid.dwSizeHid == 13)
828                         { // this report also includes rotation
829                                 short r[3] = {-axis[3], axis[5], -axis[4]};
830                                 m_ndofManager->updateRotation(r, now);
831
832                                 // I've never gotten one of these, has anyone else?
833                                 puts("ndof: combined T + R");
834                         }
835                         break;
836                 }
837                 case 2: // rotation
838                 {
839                         short* axis = (short*)(data + 1);
840                         short r[3] = {-axis[0], axis[2], -axis[1]};
841                         m_ndofManager->updateRotation(r, now);
842                         break;
843                 }
844                 case 3: // buttons
845                 {
846                         int button_bits;
847                         memcpy(&button_bits, data + 1, sizeof(button_bits));
848                         m_ndofManager->updateButtons(button_bits, now);
849                         break;
850                 }
851         }
852         return eventSent;
853 }
854 #endif // WITH_INPUT_NDOF
855
856 LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
857 {
858         GHOST_Event* event = 0;
859         bool eventHandled = false;
860
861         LRESULT lResult = 0;
862         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
863         GHOST_ASSERT(system, "GHOST_SystemWin32::s_wndProc(): system not initialized")
864
865         if (hwnd) {
866                 GHOST_WindowWin32* window = (GHOST_WindowWin32*)::GetWindowLong(hwnd, GWL_USERDATA);
867                 if (window) {
868                         switch (msg) {
869                                 // we need to check if new key layout has AltGr
870                                 case WM_INPUTLANGCHANGE:
871                                         system->handleKeyboardChange();
872                                         break;
873                                 ////////////////////////////////////////////////////////////////////////
874                                 // Keyboard events, processed
875                                 ////////////////////////////////////////////////////////////////////////
876                                 case WM_INPUT:
877                                 {
878                                         // check WM_INPUT from input sink when ghost window is not in the foreground
879                                         if (wParam == RIM_INPUTSINK) {
880                                                 if (GetFocus() != hwnd) // WM_INPUT message not for this window
881                                                         return 0;
882                                         } //else wParam == RIM_INPUT
883
884                                         RAWINPUT raw;
885                                         RAWINPUT* raw_ptr = &raw;
886                                         UINT rawSize = sizeof(RAWINPUT);
887
888                                         GetRawInputData((HRAWINPUT)lParam, RID_INPUT, raw_ptr, &rawSize, sizeof(RAWINPUTHEADER));
889
890                                         switch (raw.header.dwType)
891                                         {
892                                         case RIM_TYPEKEYBOARD:
893                                                 event = processKeyEvent(window, raw);
894                                                 if (!event) {
895                                                         GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ")
896                                                         GHOST_PRINT(msg)
897                                                         GHOST_PRINT(" key ignored\n")
898                                                 }
899                                                 break;
900 #ifdef WITH_INPUT_NDOF
901                                         case RIM_TYPEHID:
902                                                 if (system->processNDOF(raw))
903                                                         eventHandled = true;
904                                                 break;
905 #endif
906                                         }
907                                 break;
908                                 }
909                                 ////////////////////////////////////////////////////////////////////////
910                                 // Keyboard events, ignored
911                                 ////////////////////////////////////////////////////////////////////////
912                                 case WM_KEYDOWN:
913                                 case WM_SYSKEYDOWN:
914                                 case WM_KEYUP:
915                                 case WM_SYSKEYUP:
916                                         /* These functions were replaced by WM_INPUT*/
917                                 case WM_CHAR:
918                                         /* The WM_CHAR message is posted to the window with the keyboard focus when
919                                          * a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR
920                                          * contains the character code of the key that was pressed.
921                                          */
922                                 case WM_DEADCHAR:
923                                         /* The WM_DEADCHAR message is posted to the window with the keyboard focus when a
924                                          * WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR 
925                                          * specifies a character code generated by a dead key. A dead key is a key that 
926                                          * generates a character, such as the umlaut (double-dot), that is combined with 
927                                          * another character to form a composite character. For example, the umlaut-O 
928                                          * character (Ö) is generated by typing the dead key for the umlaut character, and
929                                          * then typing the O key.
930                                          */
931                                         break;
932                                 case WM_SYSDEADCHAR:
933                                         /* The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when 
934                                          * a WM_SYSKEYDOWN message is translated by the TranslateMessage function. 
935                                          * WM_SYSDEADCHAR specifies the character code of a system dead key - that is, 
936                                          * a dead key that is pressed while holding down the alt key. 
937                                          */
938                                 case WM_SYSCHAR:
939                                         /* The WM_SYSCHAR message is sent to the window with the keyboard focus when 
940                                          * a WM_SYSCHAR message is translated by the TranslateMessage function. 
941                                          * WM_SYSCHAR specifies the character code of a dead key - that is, 
942                                          * a dead key that is pressed while holding down the alt key.
943                                          * To prevent the sound, DefWindowProc must be avoided by return
944                                          */
945                                         break;
946                                 case WM_SYSCOMMAND:
947                                         /* The WM_SYSCHAR message is sent to the window when system commands such as 
948                                          * maximize, minimize  or close the window are triggered. Also it is sent when ALT 
949                                          * button is press for menu. To prevent this we must return preventing DefWindowProc.
950                                          */
951                                         if(wParam==SC_KEYMENU) return 0;
952                                         break;
953                                 ////////////////////////////////////////////////////////////////////////
954                                 // Tablet events, processed
955                                 ////////////////////////////////////////////////////////////////////////
956                                 case WT_PACKET:
957                                         ((GHOST_WindowWin32*)window)->processWin32TabletEvent(wParam, lParam);
958                                         break;
959                                 case WT_CSRCHANGE:
960                                 case WT_PROXIMITY:
961                                         ((GHOST_WindowWin32*)window)->processWin32TabletInitEvent();
962                                         break;
963                                 ////////////////////////////////////////////////////////////////////////
964                                 // Mouse events, processed
965                                 ////////////////////////////////////////////////////////////////////////
966                                 case WM_LBUTTONDOWN:
967                                         window->registerMouseClickEvent(0);
968                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskLeft);
969                                         break;
970                                 case WM_MBUTTONDOWN:
971                                         window->registerMouseClickEvent(0);
972                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskMiddle);
973                                         break;
974                                 case WM_RBUTTONDOWN:
975                                         window->registerMouseClickEvent(0);
976                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskRight);
977                                         break;
978                                 case WM_XBUTTONDOWN:
979                                         window->registerMouseClickEvent(0);
980                                         if ((short) HIWORD(wParam) == XBUTTON1){
981                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton4);
982                                         }else if((short) HIWORD(wParam) == XBUTTON2){
983                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton5);
984                                         }
985                                         break;
986                                 case WM_LBUTTONUP:
987                                         window->registerMouseClickEvent(1);
988                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskLeft);
989                                         break;
990                                 case WM_MBUTTONUP:
991                                         window->registerMouseClickEvent(1);
992                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskMiddle);
993                                         break;
994                                 case WM_RBUTTONUP:
995                                         window->registerMouseClickEvent(1);
996                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskRight);
997                                         break;
998                                 case WM_XBUTTONUP:
999                                         window->registerMouseClickEvent(1);
1000                                         if ((short) HIWORD(wParam) == XBUTTON1){
1001                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton4);
1002                                         }else if((short) HIWORD(wParam) == XBUTTON2){
1003                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton5);
1004                                         }
1005                                         break;
1006                                 case WM_MOUSEMOVE:
1007                                         event = processCursorEvent(GHOST_kEventCursorMove, window);
1008                                         break;
1009                                 case WM_MOUSEWHEEL:
1010                                         /* The WM_MOUSEWHEEL message is sent to the focus window 
1011                                          * when the mouse wheel is rotated. The DefWindowProc 
1012                                          * function propagates the message to the window's parent.
1013                                          * There should be no internal forwarding of the message, 
1014                                          * since DefWindowProc propagates it up the parent chain 
1015                                          * until it finds a window that processes it.
1016                                          */
1017                                         event = processWheelEvent(window, wParam, lParam);
1018                                         break;
1019                                 case WM_SETCURSOR:
1020                                         /* The WM_SETCURSOR message is sent to a window if the mouse causes the cursor
1021                                          * to move within a window and mouse input is not captured.
1022                                          * This means we have to set the cursor shape every time the mouse moves!
1023                                          * The DefWindowProc function uses this message to set the cursor to an 
1024                                          * arrow if it is not in the client area.
1025                                          */
1026                                         if (LOWORD(lParam) == HTCLIENT) {
1027                                                 // Load the current cursor
1028                                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
1029                                                 // Bypass call to DefWindowProc
1030                                                 return 0;
1031                                         } 
1032                                         else {
1033                                                 // Outside of client area show standard cursor
1034                                                 window->loadCursor(true, GHOST_kStandardCursorDefault);
1035                                         }
1036                                         break;
1037
1038                                 ////////////////////////////////////////////////////////////////////////
1039                                 // Mouse events, ignored
1040                                 ////////////////////////////////////////////////////////////////////////
1041                                 case WM_NCMOUSEMOVE:
1042                                         /* The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved 
1043                                          * within the nonclient area of the window. This message is posted to the window 
1044                                          * that contains the cursor. If a window has captured the mouse, this message is not posted.
1045                                          */
1046                                 case WM_NCHITTEST:
1047                                         /* The WM_NCHITTEST message is sent to a window when the cursor moves, or 
1048                                          * when a mouse button is pressed or released. If the mouse is not captured, 
1049                                          * the message is sent to the window beneath the cursor. Otherwise, the message 
1050                                          * is sent to the window that has captured the mouse. 
1051                                          */
1052                                         break;
1053
1054                                 ////////////////////////////////////////////////////////////////////////
1055                                 // Window events, processed
1056                                 ////////////////////////////////////////////////////////////////////////
1057                                 case WM_CLOSE:
1058                                         /* The WM_CLOSE message is sent as a signal that a window or an application should terminate. */
1059                                         event = processWindowEvent(GHOST_kEventWindowClose, window);
1060                                         break;
1061                                 case WM_ACTIVATE:
1062                                         /* The WM_ACTIVATE message is sent to both the window being activated and the window being 
1063                                          * deactivated. If the windows use the same input queue, the message is sent synchronously, 
1064                                          * first to the window procedure of the top-level window being deactivated, then to the window
1065                                          * procedure of the top-level window being activated. If the windows use different input queues,
1066                                          * the message is sent asynchronously, so the window is activated immediately. 
1067                                          */
1068                                         {
1069                                         GHOST_ModifierKeys modifiers;
1070                                         modifiers.clear();
1071                                         system->storeModifierKeys(modifiers);
1072                                         event = processWindowEvent(LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
1073                                         /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
1074                                         will not be dispatched to OUR active window if we minimize one of OUR windows. */
1075                                         lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
1076                                         break;
1077                                         }
1078                                 case WM_PAINT:
1079                                         /* An application sends the WM_PAINT message when the system or another application 
1080                                          * makes a request to paint a portion of an application's window. The message is sent
1081                                          * when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage 
1082                                          * function when the application obtains a WM_PAINT message by using the GetMessage or 
1083                                          * PeekMessage function. 
1084                                          */
1085                                         event = processWindowEvent(GHOST_kEventWindowUpdate, window);
1086                                         ::ValidateRect(hwnd, NULL);
1087                                         break;
1088                                 case WM_GETMINMAXINFO:
1089                                         /* The WM_GETMINMAXINFO message is sent to a window when the size or 
1090                                          * position of the window is about to change. An application can use 
1091                                          * this message to override the window's default maximized size and 
1092                                          * position, or its default minimum or maximum tracking size. 
1093                                          */
1094                                         processMinMaxInfo((MINMAXINFO *) lParam);
1095                                         /* Let DefWindowProc handle it. */
1096                                         break;
1097                                 case WM_SIZE:
1098                                         /* The WM_SIZE message is sent to a window after its size has changed.
1099                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1100                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1101                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1102                                          * message without calling DefWindowProc.
1103                                          */
1104                                         event = processWindowEvent(GHOST_kEventWindowSize, window);
1105                                         break;
1106                                 case WM_CAPTURECHANGED:
1107                                         window->lostMouseCapture();
1108                                         break;
1109                                 case WM_MOVING:
1110                                         /* The WM_MOVING message is sent to a window that the user is moving. By processing 
1111                                          * this message, an application can monitor the size and position of the drag rectangle
1112                                          * and, if needed, change its size or position.
1113                                          */
1114                                 case WM_MOVE:
1115                                         /* The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1116                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1117                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1118                                          * message without calling DefWindowProc. 
1119                                          */
1120                                         event = processWindowEvent(GHOST_kEventWindowMove, window);
1121                                         break;
1122                                 ////////////////////////////////////////////////////////////////////////
1123                                 // Window events, ignored
1124                                 ////////////////////////////////////////////////////////////////////////
1125                                 case WM_WINDOWPOSCHANGED:
1126                                         /* The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place
1127                                          * in the Z order has changed as a result of a call to the SetWindowPos function or 
1128                                          * another window-management function.
1129                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1130                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1131                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1132                                          * message without calling DefWindowProc.
1133                                          */
1134                                 case WM_ERASEBKGND:
1135                                         /* An application sends the WM_ERASEBKGND message when the window background must be 
1136                                          * erased (for example, when a window is resized). The message is sent to prepare an 
1137                                          * invalidated portion of a window for painting. 
1138                                          */
1139                                 case WM_NCPAINT:
1140                                         /* An application sends the WM_NCPAINT message to a window when its frame must be painted. */
1141                                 case WM_NCACTIVATE:
1142                                         /* The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed 
1143                                          * to indicate an active or inactive state. 
1144                                          */
1145                                 case WM_DESTROY:
1146                                         /* The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window 
1147                                          * procedure of the window being destroyed after the window is removed from the screen. 
1148                                          * This message is sent first to the window being destroyed and then to the child windows 
1149                                          * (if any) as they are destroyed. During the processing of the message, it can be assumed 
1150                                          * that all child windows still exist. 
1151                                          */
1152                                 case WM_NCDESTROY:
1153                                         /* The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The 
1154                                          * DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY
1155                                          * message. WM_DESTROY is used to free the allocated memory object associated with the window. 
1156                                          */
1157                                         break;
1158                                 case WM_KILLFOCUS:
1159                                         /* The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus. 
1160                                          * We want to prevent this if a window is still active and it loses focus to nowhere*/
1161                                         if(!wParam && hwnd==GetActiveWindow())
1162                                                 SetFocus(hwnd);
1163                                 case WM_SHOWWINDOW:
1164                                         /* The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown. */
1165                                 case WM_WINDOWPOSCHANGING:
1166                                         /* The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in 
1167                                          * the Z order is about to change as a result of a call to the SetWindowPos function or 
1168                                          * another window-management function. 
1169                                          */
1170                                 case WM_SETFOCUS:
1171                                         /* The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus. */
1172                                 case WM_ENTERSIZEMOVE:
1173                                         /* The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving 
1174                                          * or sizing modal loop. The window enters the moving or sizing modal loop when the user 
1175                                          * clicks the window's title bar or sizing border, or when the window passes the 
1176                                          * WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the 
1177                                          * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when 
1178                                          * DefWindowProc returns. 
1179                                          */
1180                                         break;
1181                                         
1182                                 ////////////////////////////////////////////////////////////////////////
1183                                 // Other events
1184                                 ////////////////////////////////////////////////////////////////////////
1185                                 case WM_GETTEXT:
1186                                         /* An application sends a WM_GETTEXT message to copy the text that 
1187                                          * corresponds to a window into a buffer provided by the caller. 
1188                                          */
1189                                 case WM_ACTIVATEAPP:
1190                                         /* The WM_ACTIVATEAPP message is sent when a window belonging to a 
1191                                          * different application than the active window is about to be activated.
1192                                          * The message is sent to the application whose window is being activated
1193                                          * and to the application whose window is being deactivated. 
1194                                          */
1195                                 case WM_TIMER:
1196                                         /* The WIN32 docs say:
1197                                          * The WM_TIMER message is posted to the installing thread's message queue
1198                                          * when a timer expires. You can process the message by providing a WM_TIMER
1199                                          * case in the window procedure. Otherwise, the default window procedure will
1200                                          * call the TimerProc callback function specified in the call to the SetTimer
1201                                          * function used to install the timer. 
1202                                          *
1203                                          * In GHOST, we let DefWindowProc call the timer callback.
1204                                          */
1205                                         break;
1206                         }
1207                 }
1208                 else {
1209                         // Event found for a window before the pointer to the class has been set.
1210                         GHOST_PRINT("GHOST_SystemWin32::wndProc: GHOST window event before creation\n")
1211                         /* These are events we typically miss at this point:
1212                            WM_GETMINMAXINFO     0x24
1213                            WM_NCCREATE                  0x81
1214                            WM_NCCALCSIZE                0x83
1215                            WM_CREATE                    0x01
1216                            We let DefWindowProc do the work.
1217                         */
1218                 }
1219         }
1220         else {
1221                 // Events without valid hwnd
1222                 GHOST_PRINT("GHOST_SystemWin32::wndProc: event without window\n")
1223         }
1224
1225         if (event) {
1226                 system->pushEvent(event);
1227                 eventHandled = true;
1228         }
1229
1230         if (!eventHandled)
1231                 lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
1232
1233         return lResult;
1234 }
1235
1236 GHOST_TUns8* GHOST_SystemWin32::getClipboard(bool selection) const 
1237 {
1238         char *buffer;
1239         char *temp_buff;
1240         
1241         if ( IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL) ) {
1242                 size_t len = 0;
1243                 HANDLE hData = GetClipboardData( CF_TEXT );
1244                 if (hData == NULL) {
1245                         CloseClipboard();
1246                         return NULL;
1247                 }
1248                 buffer = (char*)GlobalLock( hData );
1249                 if (!buffer) {
1250                         CloseClipboard();
1251                         return NULL;
1252                 }
1253                 
1254                 len = strlen(buffer);
1255                 temp_buff = (char*) malloc(len+1);
1256                 strncpy(temp_buff, buffer, len);
1257                 temp_buff[len] = '\0';
1258                 
1259                 /* Buffer mustn't be accessed after CloseClipboard
1260                    it would like accessing free-d memory */
1261                 GlobalUnlock( hData );
1262                 CloseClipboard();
1263                 
1264                 return (GHOST_TUns8*)temp_buff;
1265         } else {
1266                 return NULL;
1267         }
1268 }
1269
1270 void GHOST_SystemWin32::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1271 {
1272         if(selection) {return;} // for copying the selection, used on X11
1273
1274         if (OpenClipboard(NULL)) {
1275                 HLOCAL clipbuffer;
1276                 char *data;
1277                 
1278                 if (buffer) {
1279                         EmptyClipboard();
1280                         
1281                         clipbuffer = LocalAlloc(LMEM_FIXED,((strlen(buffer)+1)));
1282                         data = (char*)GlobalLock(clipbuffer);
1283
1284                         strcpy(data, (char*)buffer);
1285                         data[strlen(buffer)] = '\0';
1286                         LocalUnlock(clipbuffer);
1287                         SetClipboardData(CF_TEXT,clipbuffer);
1288                 }
1289                 CloseClipboard();
1290         } else {
1291                 return;
1292         }
1293 }
1294
1295 int GHOST_SystemWin32::toggleConsole(int action)
1296 {
1297         switch(action)
1298         {
1299                 case 3: //hide if no console
1300                         {
1301                                 DWORD sp = GetCurrentProcessId();
1302                                 HANDLE ptree = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
1303                                 PROCESSENTRY32 e = {0}; e.dwSize = sizeof(PROCESSENTRY32);
1304                                 
1305                                 if( Process32First(ptree, &e)) {
1306                                         do { //Searches for Blender's PROCESSENTRY32
1307                                                         if (e.th32ProcessID == sp) {
1308                                                                 sp = e.th32ParentProcessID;
1309                                                                 Process32First(ptree, &e);
1310                                                                         do { //Got parent id, searches for its PROCESSENTRY32
1311                                                                                 if (e.th32ProcessID == sp) {
1312                                                                                         if(strcmp("explorer.exe",e.szExeFile)==0)
1313                                                                                         { //If explorer, hide cmd
1314                                                                                                 ShowWindow(GetConsoleWindow(),SW_HIDE);
1315                                                                                                 m_consoleStatus = 0;
1316                                                                                         }
1317                                                                                         break;
1318                                                                                 }
1319
1320                                                                         } while( Process32Next(ptree, &e));
1321                                                                 break;
1322                                                         }
1323                                         } while( Process32Next(ptree, &e));
1324                                 }
1325
1326                                 CloseHandle(ptree);
1327                                 break;
1328                         }
1329                 case 0: //hide
1330                         ShowWindow(GetConsoleWindow(),SW_HIDE);
1331                         m_consoleStatus = 0;
1332                         break;
1333                 case 1: //show
1334                         ShowWindow(GetConsoleWindow(),SW_SHOW);
1335                         m_consoleStatus = 1;
1336                         break;
1337                 case 2: //toggle
1338                         ShowWindow(GetConsoleWindow(),m_consoleStatus?SW_HIDE:SW_SHOW);
1339                         m_consoleStatus=!m_consoleStatus;
1340                         break;
1341
1342         };
1343
1344
1345         return m_consoleStatus;
1346 }