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