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