code cleanup: add getCursorGrabModeIsWarp(), makes the intent more clear where we...
[blender.git] / intern / ghost / intern / GHOST_SystemWin32.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file ghost/intern/GHOST_SystemWin32.cpp
29  *  \ingroup GHOST
30  */
31
32
33 /**
34
35  * Copyright (C) 2001 NaN Technologies B.V.
36  * @author      Maarten Gribnau
37  * @date        May 7, 2001
38  */
39
40 #ifdef BF_GHOST_DEBUG
41 #include <iostream>
42 #endif
43
44 #include <stdio.h> // [mce] temporary debug, remove soon!
45
46 #include "GHOST_SystemWin32.h"
47 #include "GHOST_EventDragnDrop.h"
48
49 #ifndef _WIN32_IE
50 #define _WIN32_IE 0x0501 /* shipped before XP, so doesn't impose additional requirements */
51 #endif
52 #include <shlobj.h>
53 #include <tlhelp32.h>
54
55 // win64 doesn't define GWL_USERDATA
56 #ifdef WIN32
57 #ifndef GWL_USERDATA
58 #define GWL_USERDATA GWLP_USERDATA
59 #define GWL_WNDPROC GWLP_WNDPROC 
60 #endif
61 #endif
62
63 #include "utfconv.h"
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 (::PeekMessageW(&msg, 0, 0, 0, PM_REMOVE) != 0) {
298                         ::DispatchMessageW(&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                 WNDCLASSW 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= L"GHOST_WindowClass";
414
415                 // Use RegisterClassEx for setting small icon
416                 if (::RegisterClassW(&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         // RI_KEY_BREAK doesn't work for sticky keys release, so we also
445         // check for the up message
446         unsigned int msg = raw.data.keyboard.Message;
447         *keyDown = !(raw.data.keyboard.Flags & RI_KEY_BREAK) && msg != WM_KEYUP && msg != WM_SYSKEYUP;
448
449         key = this->convertKey(window, raw.data.keyboard.VKey, raw.data.keyboard.MakeCode, (raw.data.keyboard.Flags&(RI_KEY_E1|RI_KEY_E0)));
450         
451         // extra handling of modifier keys: don't send repeats out from GHOST
452         if(key >= GHOST_kKeyLeftShift && key <= GHOST_kKeyRightAlt)
453         {
454                 bool changed = false;
455                 GHOST_TModifierKeyMask modifier;
456                 switch(key) {
457                         case GHOST_kKeyLeftShift:
458                                 {
459                                         changed = (modifiers.get(GHOST_kModifierKeyLeftShift) != (bool)*keyDown);
460                                         modifier = GHOST_kModifierKeyLeftShift;
461                                 }
462                                 break;
463                         case GHOST_kKeyRightShift:
464                                 {
465                                         changed = (modifiers.get(GHOST_kModifierKeyRightShift) != (bool)*keyDown);
466                                         modifier = GHOST_kModifierKeyRightShift;
467                                 }
468                                 break;
469                         case GHOST_kKeyLeftControl:
470                                 {
471                                         changed = (modifiers.get(GHOST_kModifierKeyLeftControl) != (bool)*keyDown);
472                                         modifier = GHOST_kModifierKeyLeftControl;
473                                 }
474                                 break;
475                         case GHOST_kKeyRightControl:
476                                 {
477                                         changed = (modifiers.get(GHOST_kModifierKeyRightControl) != (bool)*keyDown);
478                                         modifier = GHOST_kModifierKeyRightControl;
479                                 }
480                                 break;
481                         case GHOST_kKeyLeftAlt:
482                                 {
483                                         changed = (modifiers.get(GHOST_kModifierKeyLeftAlt) != (bool)*keyDown);
484                                         modifier = GHOST_kModifierKeyLeftAlt;
485                                 }
486                                 break;
487                         case GHOST_kKeyRightAlt:
488                                 {
489                                         changed = (modifiers.get(GHOST_kModifierKeyRightAlt) != (bool)*keyDown);
490                                         modifier = GHOST_kModifierKeyRightAlt;
491                                 }
492                                 break;
493                         default: break;
494                 }
495                 
496                 if(changed)
497                 {
498                         modifiers.set(modifier, (bool)*keyDown);
499                         system->storeModifierKeys(modifiers);
500                 }
501                 else
502                 {
503                         key = GHOST_kKeyUnknown;
504                 }
505         }
506         
507
508         if(vk) *vk = raw.data.keyboard.VKey;
509
510         return key;
511 }
512
513 //! note: this function can be extended to include other exotic cases as they arise.
514 // This function was added in response to bug [#25715]
515 GHOST_TKey GHOST_SystemWin32::processSpecialKey(GHOST_IWindow *window, short vKey, short scanCode) const
516 {
517         GHOST_TKey key = GHOST_kKeyUnknown;
518         switch(PRIMARYLANGID(m_langId)) {
519                 case LANG_FRENCH:
520                         if(vKey==VK_OEM_8) key = GHOST_kKeyF13; // oem key; used purely for shortcuts .
521                         break;
522         }
523
524         return key;
525 }
526
527 GHOST_TKey GHOST_SystemWin32::convertKey(GHOST_IWindow *window, short vKey, short scanCode, short extend) const
528 {
529         GHOST_TKey key;
530
531         if ((vKey >= '0') && (vKey <= '9')) {
532                 // VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
533                 key = (GHOST_TKey)(vKey - '0' + GHOST_kKey0);
534         }
535         else if ((vKey >= 'A') && (vKey <= 'Z')) {
536                 // VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
537                 key = (GHOST_TKey)(vKey - 'A' + GHOST_kKeyA);
538         }
539         else if ((vKey >= VK_F1) && (vKey <= VK_F24)) {
540                 key = (GHOST_TKey)(vKey - VK_F1 + GHOST_kKeyF1);
541         }
542         else {
543                 switch (vKey) {
544                 case VK_RETURN:
545                                 key = (extend)?GHOST_kKeyNumpadEnter : GHOST_kKeyEnter; break;
546                         
547                 case VK_BACK:     key = GHOST_kKeyBackSpace;            break;
548                 case VK_TAB:      key = GHOST_kKeyTab;                          break;
549                 case VK_ESCAPE:   key = GHOST_kKeyEsc;                          break;
550                 case VK_SPACE:    key = GHOST_kKeySpace;                        break;
551                 
552                 case VK_INSERT:
553                 case VK_NUMPAD0:
554                         key = (extend) ? GHOST_kKeyInsert : GHOST_kKeyNumpad0;  break;
555                 case VK_END:
556                 case VK_NUMPAD1:        
557                         key = (extend) ? GHOST_kKeyEnd : GHOST_kKeyNumpad1;     break;
558                 case VK_DOWN:
559                 case VK_NUMPAD2:
560                         key = (extend) ? GHOST_kKeyDownArrow : GHOST_kKeyNumpad2;       break;
561                 case VK_NEXT:
562                 case VK_NUMPAD3:
563                         key = (extend) ?  GHOST_kKeyDownPage : GHOST_kKeyNumpad3;       break;
564                 case VK_LEFT:
565                 case VK_NUMPAD4:
566                         key = (extend) ? GHOST_kKeyLeftArrow : GHOST_kKeyNumpad4;       break;
567                 case VK_CLEAR:
568                 case VK_NUMPAD5:
569                         key = (extend) ? GHOST_kKeyUnknown: GHOST_kKeyNumpad5;  break;
570                 case VK_RIGHT:
571                 case VK_NUMPAD6:
572                         key = (extend) ? GHOST_kKeyRightArrow : GHOST_kKeyNumpad6;      break;
573                 case VK_HOME:
574                 case VK_NUMPAD7:
575                         key = (extend) ? GHOST_kKeyHome : GHOST_kKeyNumpad7;    break;
576                 case VK_UP:
577                 case VK_NUMPAD8:
578                         key = (extend) ? GHOST_kKeyUpArrow : GHOST_kKeyNumpad8; break;
579                 case VK_PRIOR:
580                 case VK_NUMPAD9:
581                         key = (extend) ? GHOST_kKeyUpPage : GHOST_kKeyNumpad9;  break;
582                 case VK_DECIMAL:
583                 case VK_DELETE:
584                         key = (extend) ? GHOST_kKeyDelete : GHOST_kKeyNumpadPeriod;     break;
585
586                 case VK_SNAPSHOT: key = GHOST_kKeyPrintScreen;          break;
587                 case VK_PAUSE:    key = GHOST_kKeyPause;                        break;
588                 case VK_MULTIPLY: key = GHOST_kKeyNumpadAsterisk;       break;
589                 case VK_SUBTRACT: key = GHOST_kKeyNumpadMinus;          break;
590                 case VK_DIVIDE:   key = GHOST_kKeyNumpadSlash;          break;
591                 case VK_ADD:      key = GHOST_kKeyNumpadPlus;           break;
592
593                 case VK_SEMICOLON:              key = GHOST_kKeySemicolon;              break;
594                 case VK_EQUALS:                 key = GHOST_kKeyEqual;                  break;
595                 case VK_COMMA:                  key = GHOST_kKeyComma;                  break;
596                 case VK_MINUS:                  key = GHOST_kKeyMinus;                  break;
597                 case VK_PERIOD:                 key = GHOST_kKeyPeriod;                 break;
598                 case VK_SLASH:                  key = GHOST_kKeySlash;                  break;
599                 case VK_BACK_QUOTE:             key = GHOST_kKeyAccentGrave;    break;
600                 case VK_OPEN_BRACKET:   key = GHOST_kKeyLeftBracket;    break;
601                 case VK_BACK_SLASH:             key = GHOST_kKeyBackslash;              break;
602                 case VK_CLOSE_BRACKET:  key = GHOST_kKeyRightBracket;   break;
603                 case VK_QUOTE:                  key = GHOST_kKeyQuote;                  break;
604                 case VK_GR_LESS:                key = GHOST_kKeyGrLess;                 break;
605
606                 case VK_SHIFT:
607                         key = (scanCode == 0x36)? GHOST_kKeyRightShift : GHOST_kKeyLeftShift;
608                         break;
609                 case VK_CONTROL:
610                         key = (extend)? GHOST_kKeyRightControl : GHOST_kKeyLeftControl;
611                         break;
612                 case VK_MENU:
613                         key = (extend)? GHOST_kKeyRightAlt : GHOST_kKeyLeftAlt;
614                         break;
615                 case VK_LWIN:
616                 case VK_RWIN:
617                         key = GHOST_kKeyOS;
618                         break;
619                 case VK_NUMLOCK: key = GHOST_kKeyNumLock; break;
620                 case VK_SCROLL: key = GHOST_kKeyScrollLock; break;
621                 case VK_CAPITAL: key = GHOST_kKeyCapsLock; break;
622                 case VK_OEM_8:
623                         key = ((GHOST_SystemWin32*)getSystem())->processSpecialKey(window, vKey, scanCode);
624                         break;
625                 case VK_MEDIA_PLAY_PAUSE: key = GHOST_kKeyMediaPlay; break;
626                 case VK_MEDIA_STOP: key = GHOST_kKeyMediaStop; break;
627                 case VK_MEDIA_PREV_TRACK: key = GHOST_kKeyMediaFirst; break;
628                 case VK_MEDIA_NEXT_TRACK: key = GHOST_kKeyMediaLast; break;
629                 default:
630                         key = GHOST_kKeyUnknown;
631                         break;
632                 }
633         }
634         
635         return key;
636 }
637
638 GHOST_EventButton* GHOST_SystemWin32::processButtonEvent(GHOST_TEventType type, GHOST_IWindow *window, GHOST_TButtonMask mask)
639 {
640         return new GHOST_EventButton (getSystem()->getMilliSeconds(), type, window, mask);
641 }
642
643
644 GHOST_EventCursor* GHOST_SystemWin32::processCursorEvent(GHOST_TEventType type, GHOST_IWindow *Iwindow)
645 {
646         GHOST_TInt32 x_screen, y_screen;
647         GHOST_SystemWin32 * system = ((GHOST_SystemWin32 * ) getSystem());
648         GHOST_WindowWin32 * window = ( GHOST_WindowWin32 * ) Iwindow;
649         
650         system->getCursorPosition(x_screen, y_screen);
651
652         /* TODO: CHECK IF THIS IS A TABLET EVENT */
653         bool is_tablet = false;
654
655         if (is_tablet == false && window->getCursorGrabModeIsWarp()) {
656                 GHOST_TInt32 x_new= x_screen;
657                 GHOST_TInt32 y_new= y_screen;
658                 GHOST_TInt32 x_accum, y_accum;
659                 GHOST_Rect bounds;
660
661                 /* fallback to window bounds */
662                 if(window->getCursorGrabBounds(bounds)==GHOST_kFailure){
663                         window->getClientBounds(bounds);
664                 }
665
666                 /* could also clamp to screen bounds
667                  * wrap with a window outside the view will fail atm  */
668
669                 bounds.wrapPoint(x_new, y_new, 2); /* offset of one incase blender is at screen bounds */
670
671                 window->getCursorGrabAccum(x_accum, y_accum);
672                 if(x_new != x_screen|| y_new != y_screen) {
673                         /* when wrapping we don't need to add an event because the
674                          * setCursorPosition call will cause a new event after */
675                         system->setCursorPosition(x_new, y_new); /* wrap */
676                         window->setCursorGrabAccum(x_accum + (x_screen - x_new), y_accum + (y_screen - y_new));
677                 }else{
678                         return new GHOST_EventCursor(system->getMilliSeconds(),
679                                                                                  GHOST_kEventCursorMove,
680                                                                                  window,
681                                                                                  x_screen + x_accum,
682                                                                                  y_screen + y_accum
683                         );
684                 }
685
686         }
687         else {
688                 return new GHOST_EventCursor(system->getMilliSeconds(),
689                                                                          GHOST_kEventCursorMove,
690                                                                          window,
691                                                                          x_screen,
692                                                                          y_screen
693                 );
694         }
695         return NULL;
696 }
697
698
699 GHOST_EventWheel* GHOST_SystemWin32::processWheelEvent(GHOST_IWindow *window, WPARAM wParam, LPARAM lParam)
700 {
701         // short fwKeys = LOWORD(wParam);                       // key flags
702         int zDelta = (short) HIWORD(wParam);    // wheel rotation
703         
704         // zDelta /= WHEEL_DELTA;
705         // temporary fix below: microsoft now has added more precision, making the above division not work
706         if (zDelta <= 0 ) zDelta= -1; else zDelta= 1;   
707         
708         // short xPos = (short) LOWORD(lParam); // horizontal position of pointer
709         // short yPos = (short) HIWORD(lParam); // vertical position of pointer
710         return new GHOST_EventWheel (getSystem()->getMilliSeconds(), window, zDelta);
711 }
712
713
714 GHOST_EventKey* GHOST_SystemWin32::processKeyEvent(GHOST_IWindow *window, RAWINPUT const& raw)
715 {
716         int keyDown=0;
717         char vk;
718         GHOST_SystemWin32 * system = (GHOST_SystemWin32 *)getSystem();
719         GHOST_TKey key = system->hardKey(window, raw, &keyDown, &vk);
720         GHOST_EventKey* event;
721
722         if (key != GHOST_kKeyUnknown) {
723                 char utf8_char[6] = {0};
724                 char ascii = 0;
725
726                 wchar_t utf16[3]={0};
727                 BYTE state[256] ={0};
728                 int r;
729                 GetKeyboardState((PBYTE)state);
730
731                 if(r = ToUnicodeEx(vk, 0, state, utf16, 2, 0, system->m_keylayout)) {
732                         if((r>0 && r<3)){
733                                 utf16[r]=0;
734                                 conv_utf_16_to_8(utf16,utf8_char,6);
735                         }
736                         else if (r==-1) {
737                                 utf8_char[0] = '\0';
738                         }
739                 }
740
741                 if(!keyDown) {
742                         utf8_char[0] = '\0';
743                         ascii='\0';
744                 }
745                 else {
746                         ascii = utf8_char[0]& 0x80?'?' : utf8_char[0];
747                 }
748
749                 if(0x80&state[VK_MENU]) utf8_char[0]='\0';
750
751                 event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown: GHOST_kEventKeyUp, window, key, ascii, utf8_char);
752                 
753 #ifdef GHOST_DEBUG
754                 std::cout << ascii << std::endl;
755 #endif
756         }
757         else {
758                 event = 0;
759         }
760         return event;
761 }
762
763
764 GHOST_Event* GHOST_SystemWin32::processWindowEvent(GHOST_TEventType type, GHOST_IWindow* window)
765 {
766         GHOST_System* system = (GHOST_System*)getSystem();
767
768         if (type == GHOST_kEventWindowActivate) {
769                 system->getWindowManager()->setActiveWindow(window);
770         }
771
772         return new GHOST_Event(system->getMilliSeconds(), type, window);
773 }
774
775 GHOST_TSuccess GHOST_SystemWin32::pushDragDropEvent(GHOST_TEventType eventType, 
776                                                                                                         GHOST_TDragnDropTypes draggedObjectType,
777                                                                                                         GHOST_IWindow* window,
778                                                                                                         int mouseX, int mouseY,
779                                                                                                         void* data)
780 {
781         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
782         return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
783                                                                                                           eventType,
784                                                                                                           draggedObjectType,
785                                                                                                           window,mouseX,mouseY,data)
786                         );
787 }
788
789 void GHOST_SystemWin32::processMinMaxInfo(MINMAXINFO * minmax)
790 {
791         minmax->ptMinTrackSize.x=320;
792         minmax->ptMinTrackSize.y=240;
793 }
794
795 #ifdef WITH_INPUT_NDOF
796 bool GHOST_SystemWin32::processNDOF(RAWINPUT const& raw)
797 {
798         bool eventSent = false;
799         GHOST_TUns64 now = getMilliSeconds();
800
801         static bool firstEvent = true;
802         if (firstEvent) { // determine exactly which device is plugged in
803                 RID_DEVICE_INFO info;
804                 unsigned infoSize = sizeof(RID_DEVICE_INFO);
805                 info.cbSize = infoSize;
806
807                 GetRawInputDeviceInfo(raw.header.hDevice, RIDI_DEVICEINFO, &info, &infoSize);
808                 if (info.dwType == RIM_TYPEHID)
809                         m_ndofManager->setDevice(info.hid.dwVendorId, info.hid.dwProductId);
810                 else
811                         puts("<!> not a HID device... mouse/kb perhaps?");
812
813                 firstEvent = false;
814         }
815
816         // The NDOF manager sends button changes immediately, and *pretends* to
817         // send motion. Mark as 'sent' so motion will always get dispatched.
818         eventSent = true;
819
820 #if defined(_MSC_VER) || defined(FREE_WINDOWS64)
821         // using Microsoft compiler & header files
822         // they invented the RawInput API, so this version is (probably) correct.
823         // MinGW64 also works fine with this
824         BYTE const* data = raw.data.hid.bRawData;
825         // struct RAWHID {
826         // DWORD dwSizeHid;
827         // DWORD dwCount;
828         // BYTE  bRawData[1];
829         // };
830 #else
831         // MinGW's definition (below) doesn't agree, so we need a slight
832         // workaround until it's fixed
833         BYTE const* data = &raw.data.hid.bRawData;
834         // struct RAWHID {
835         // DWORD dwSizeHid;
836         // DWORD dwCount;
837         // BYTE bRawData; // <== isn't this s'posed to be a BYTE*?
838         // };
839 #endif
840
841         BYTE packetType = data[0];
842         switch (packetType)
843         {
844                 case 1: // translation
845                 {
846                         short* axis = (short*)(data + 1);
847                         // massage into blender view coords (same goes for rotation)
848                         short t[3] = {axis[0], -axis[2], axis[1]};
849                         m_ndofManager->updateTranslation(t, now);
850
851                         if (raw.data.hid.dwSizeHid == 13)
852                         { // this report also includes rotation
853                                 short r[3] = {-axis[3], axis[5], -axis[4]};
854                                 m_ndofManager->updateRotation(r, now);
855
856                                 // I've never gotten one of these, has anyone else?
857                                 puts("ndof: combined T + R");
858                         }
859                         break;
860                 }
861                 case 2: // rotation
862                 {
863                         short* axis = (short*)(data + 1);
864                         short r[3] = {-axis[0], axis[2], -axis[1]};
865                         m_ndofManager->updateRotation(r, now);
866                         break;
867                 }
868                 case 3: // buttons
869                 {
870                         int button_bits;
871                         memcpy(&button_bits, data + 1, sizeof(button_bits));
872                         m_ndofManager->updateButtons(button_bits, now);
873                         break;
874                 }
875         }
876         return eventSent;
877 }
878 #endif // WITH_INPUT_NDOF
879
880 LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
881 {
882         GHOST_Event* event = 0;
883         bool eventHandled = false;
884
885         LRESULT lResult = 0;
886         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
887         GHOST_ASSERT(system, "GHOST_SystemWin32::s_wndProc(): system not initialized")
888
889         if (hwnd) {
890                 GHOST_WindowWin32* window = (GHOST_WindowWin32*)::GetWindowLong(hwnd, GWL_USERDATA);
891                 if (window) {
892                         switch (msg) {
893                                 // we need to check if new key layout has AltGr
894                                 case WM_INPUTLANGCHANGE:
895                                         system->handleKeyboardChange();
896                                         break;
897                                 ////////////////////////////////////////////////////////////////////////
898                                 // Keyboard events, processed
899                                 ////////////////////////////////////////////////////////////////////////
900                                 case WM_INPUT:
901                                 {
902                                         // check WM_INPUT from input sink when ghost window is not in the foreground
903                                         if (wParam == RIM_INPUTSINK) {
904                                                 if (GetFocus() != hwnd) // WM_INPUT message not for this window
905                                                         return 0;
906                                         } //else wParam == RIM_INPUT
907
908                                         RAWINPUT raw;
909                                         RAWINPUT* raw_ptr = &raw;
910                                         UINT rawSize = sizeof(RAWINPUT);
911
912                                         GetRawInputData((HRAWINPUT)lParam, RID_INPUT, raw_ptr, &rawSize, sizeof(RAWINPUTHEADER));
913
914                                         switch (raw.header.dwType)
915                                         {
916                                         case RIM_TYPEKEYBOARD:
917                                                 event = processKeyEvent(window, raw);
918                                                 if (!event) {
919                                                         GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ")
920                                                         GHOST_PRINT(msg)
921                                                         GHOST_PRINT(" key ignored\n")
922                                                 }
923                                                 break;
924 #ifdef WITH_INPUT_NDOF
925                                         case RIM_TYPEHID:
926                                                 if (system->processNDOF(raw))
927                                                         eventHandled = true;
928                                                 break;
929 #endif
930                                         }
931                                 break;
932                                 }
933                                 ////////////////////////////////////////////////////////////////////////
934                                 // Keyboard events, ignored
935                                 ////////////////////////////////////////////////////////////////////////
936                                 case WM_KEYDOWN:
937                                 case WM_SYSKEYDOWN:
938                                 case WM_KEYUP:
939                                 case WM_SYSKEYUP:
940                                         /* These functions were replaced by WM_INPUT*/
941                                 case WM_CHAR:
942                                         /* The WM_CHAR message is posted to the window with the keyboard focus when
943                                          * a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR
944                                          * contains the character code of the key that was pressed.
945                                          */
946                                 case WM_DEADCHAR:
947                                         /* The WM_DEADCHAR message is posted to the window with the keyboard focus when a
948                                          * WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR 
949                                          * specifies a character code generated by a dead key. A dead key is a key that 
950                                          * generates a character, such as the umlaut (double-dot), that is combined with 
951                                          * another character to form a composite character. For example, the umlaut-O 
952                                          * character (Ö) is generated by typing the dead key for the umlaut character, and
953                                          * then typing the O key.
954                                          */
955                                         break;
956                                 case WM_SYSDEADCHAR:
957                                         /* The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when 
958                                          * a WM_SYSKEYDOWN message is translated by the TranslateMessage function. 
959                                          * WM_SYSDEADCHAR specifies the character code of a system dead key - that is, 
960                                          * a dead key that is pressed while holding down the alt key. 
961                                          */
962                                 case WM_SYSCHAR:
963                                         /* The WM_SYSCHAR message is sent to the window with the keyboard focus when 
964                                          * a WM_SYSCHAR message is translated by the TranslateMessage function. 
965                                          * WM_SYSCHAR specifies the character code of a dead key - that is, 
966                                          * a dead key that is pressed while holding down the alt key.
967                                          * To prevent the sound, DefWindowProc must be avoided by return
968                                          */
969                                         break;
970                                 case WM_SYSCOMMAND:
971                                         /* The WM_SYSCHAR message is sent to the window when system commands such as 
972                                          * maximize, minimize  or close the window are triggered. Also it is sent when ALT 
973                                          * button is press for menu. To prevent this we must return preventing DefWindowProc.
974                                          */
975                                         if(wParam==SC_KEYMENU) return 0;
976                                         break;
977                                 ////////////////////////////////////////////////////////////////////////
978                                 // Tablet events, processed
979                                 ////////////////////////////////////////////////////////////////////////
980                                 case WT_PACKET:
981                                         ((GHOST_WindowWin32*)window)->processWin32TabletEvent(wParam, lParam);
982                                         break;
983                                 case WT_CSRCHANGE:
984                                 case WT_PROXIMITY:
985                                         ((GHOST_WindowWin32*)window)->processWin32TabletInitEvent();
986                                         break;
987                                 ////////////////////////////////////////////////////////////////////////
988                                 // Mouse events, processed
989                                 ////////////////////////////////////////////////////////////////////////
990                                 case WM_LBUTTONDOWN:
991                                         window->registerMouseClickEvent(0);
992                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskLeft);
993                                         break;
994                                 case WM_MBUTTONDOWN:
995                                         window->registerMouseClickEvent(0);
996                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskMiddle);
997                                         break;
998                                 case WM_RBUTTONDOWN:
999                                         window->registerMouseClickEvent(0);
1000                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskRight);
1001                                         break;
1002                                 case WM_XBUTTONDOWN:
1003                                         window->registerMouseClickEvent(0);
1004                                         if ((short) HIWORD(wParam) == XBUTTON1){
1005                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton4);
1006                                         }else if((short) HIWORD(wParam) == XBUTTON2){
1007                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton5);
1008                                         }
1009                                         break;
1010                                 case WM_LBUTTONUP:
1011                                         window->registerMouseClickEvent(1);
1012                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskLeft);
1013                                         break;
1014                                 case WM_MBUTTONUP:
1015                                         window->registerMouseClickEvent(1);
1016                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskMiddle);
1017                                         break;
1018                                 case WM_RBUTTONUP:
1019                                         window->registerMouseClickEvent(1);
1020                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskRight);
1021                                         break;
1022                                 case WM_XBUTTONUP:
1023                                         window->registerMouseClickEvent(1);
1024                                         if ((short) HIWORD(wParam) == XBUTTON1){
1025                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton4);
1026                                         }else if((short) HIWORD(wParam) == XBUTTON2){
1027                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton5);
1028                                         }
1029                                         break;
1030                                 case WM_MOUSEMOVE:
1031                                         event = processCursorEvent(GHOST_kEventCursorMove, window);
1032                                         break;
1033                                 case WM_MOUSEWHEEL:
1034                                         /* The WM_MOUSEWHEEL message is sent to the focus window 
1035                                          * when the mouse wheel is rotated. The DefWindowProc 
1036                                          * function propagates the message to the window's parent.
1037                                          * There should be no internal forwarding of the message, 
1038                                          * since DefWindowProc propagates it up the parent chain 
1039                                          * until it finds a window that processes it.
1040                                          */
1041                                         event = processWheelEvent(window, wParam, lParam);
1042                                         break;
1043                                 case WM_SETCURSOR:
1044                                         /* The WM_SETCURSOR message is sent to a window if the mouse causes the cursor
1045                                          * to move within a window and mouse input is not captured.
1046                                          * This means we have to set the cursor shape every time the mouse moves!
1047                                          * The DefWindowProc function uses this message to set the cursor to an 
1048                                          * arrow if it is not in the client area.
1049                                          */
1050                                         if (LOWORD(lParam) == HTCLIENT) {
1051                                                 // Load the current cursor
1052                                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
1053                                                 // Bypass call to DefWindowProc
1054                                                 return 0;
1055                                         } 
1056                                         else {
1057                                                 // Outside of client area show standard cursor
1058                                                 window->loadCursor(true, GHOST_kStandardCursorDefault);
1059                                         }
1060                                         break;
1061
1062                                 ////////////////////////////////////////////////////////////////////////
1063                                 // Mouse events, ignored
1064                                 ////////////////////////////////////////////////////////////////////////
1065                                 case WM_NCMOUSEMOVE:
1066                                         /* The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved 
1067                                          * within the nonclient area of the window. This message is posted to the window 
1068                                          * that contains the cursor. If a window has captured the mouse, this message is not posted.
1069                                          */
1070                                 case WM_NCHITTEST:
1071                                         /* The WM_NCHITTEST message is sent to a window when the cursor moves, or 
1072                                          * when a mouse button is pressed or released. If the mouse is not captured, 
1073                                          * the message is sent to the window beneath the cursor. Otherwise, the message 
1074                                          * is sent to the window that has captured the mouse. 
1075                                          */
1076                                         break;
1077
1078                                 ////////////////////////////////////////////////////////////////////////
1079                                 // Window events, processed
1080                                 ////////////////////////////////////////////////////////////////////////
1081                                 case WM_CLOSE:
1082                                         /* The WM_CLOSE message is sent as a signal that a window or an application should terminate. */
1083                                         event = processWindowEvent(GHOST_kEventWindowClose, window);
1084                                         break;
1085                                 case WM_ACTIVATE:
1086                                         /* The WM_ACTIVATE message is sent to both the window being activated and the window being 
1087                                          * deactivated. If the windows use the same input queue, the message is sent synchronously, 
1088                                          * first to the window procedure of the top-level window being deactivated, then to the window
1089                                          * procedure of the top-level window being activated. If the windows use different input queues,
1090                                          * the message is sent asynchronously, so the window is activated immediately. 
1091                                          */
1092                                         {
1093                                         GHOST_ModifierKeys modifiers;
1094                                         modifiers.clear();
1095                                         system->storeModifierKeys(modifiers);
1096                                         event = processWindowEvent(LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
1097                                         /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
1098                                         will not be dispatched to OUR active window if we minimize one of OUR windows. */
1099                                         lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
1100                                         break;
1101                                         }
1102                                 case WM_PAINT:
1103                                         /* An application sends the WM_PAINT message when the system or another application 
1104                                          * makes a request to paint a portion of an application's window. The message is sent
1105                                          * when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage 
1106                                          * function when the application obtains a WM_PAINT message by using the GetMessage or 
1107                                          * PeekMessage function. 
1108                                          */
1109                                         event = processWindowEvent(GHOST_kEventWindowUpdate, window);
1110                                         ::ValidateRect(hwnd, NULL);
1111                                         break;
1112                                 case WM_GETMINMAXINFO:
1113                                         /* The WM_GETMINMAXINFO message is sent to a window when the size or 
1114                                          * position of the window is about to change. An application can use 
1115                                          * this message to override the window's default maximized size and 
1116                                          * position, or its default minimum or maximum tracking size. 
1117                                          */
1118                                         processMinMaxInfo((MINMAXINFO *) lParam);
1119                                         /* Let DefWindowProc handle it. */
1120                                         break;
1121                                 case WM_SIZE:
1122                                         /* The WM_SIZE message is sent to a window after its size has changed.
1123                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1124                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1125                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1126                                          * message without calling DefWindowProc.
1127                                          */
1128                                         event = processWindowEvent(GHOST_kEventWindowSize, window);
1129                                         break;
1130                                 case WM_CAPTURECHANGED:
1131                                         window->lostMouseCapture();
1132                                         break;
1133                                 case WM_MOVING:
1134                                         /* The WM_MOVING message is sent to a window that the user is moving. By processing 
1135                                          * this message, an application can monitor the size and position of the drag rectangle
1136                                          * and, if needed, change its size or position.
1137                                          */
1138                                 case WM_MOVE:
1139                                         /* The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1140                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1141                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1142                                          * message without calling DefWindowProc. 
1143                                          */
1144                                         event = processWindowEvent(GHOST_kEventWindowMove, window);
1145                                         break;
1146                                 ////////////////////////////////////////////////////////////////////////
1147                                 // Window events, ignored
1148                                 ////////////////////////////////////////////////////////////////////////
1149                                 case WM_WINDOWPOSCHANGED:
1150                                         /* The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place
1151                                          * in the Z order has changed as a result of a call to the SetWindowPos function or 
1152                                          * another window-management function.
1153                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1154                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1155                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1156                                          * message without calling DefWindowProc.
1157                                          */
1158                                 case WM_ERASEBKGND:
1159                                         /* An application sends the WM_ERASEBKGND message when the window background must be 
1160                                          * erased (for example, when a window is resized). The message is sent to prepare an 
1161                                          * invalidated portion of a window for painting. 
1162                                          */
1163                                 case WM_NCPAINT:
1164                                         /* An application sends the WM_NCPAINT message to a window when its frame must be painted. */
1165                                 case WM_NCACTIVATE:
1166                                         /* The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed 
1167                                          * to indicate an active or inactive state. 
1168                                          */
1169                                 case WM_DESTROY:
1170                                         /* The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window 
1171                                          * procedure of the window being destroyed after the window is removed from the screen. 
1172                                          * This message is sent first to the window being destroyed and then to the child windows 
1173                                          * (if any) as they are destroyed. During the processing of the message, it can be assumed 
1174                                          * that all child windows still exist. 
1175                                          */
1176                                 case WM_NCDESTROY:
1177                                         /* The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The 
1178                                          * DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY
1179                                          * message. WM_DESTROY is used to free the allocated memory object associated with the window. 
1180                                          */
1181                                         break;
1182                                 case WM_KILLFOCUS:
1183                                         /* The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus. 
1184                                          * We want to prevent this if a window is still active and it loses focus to nowhere*/
1185                                         if(!wParam && hwnd==GetActiveWindow())
1186                                                 SetFocus(hwnd);
1187                                 case WM_SHOWWINDOW:
1188                                         /* The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown. */
1189                                 case WM_WINDOWPOSCHANGING:
1190                                         /* The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in 
1191                                          * the Z order is about to change as a result of a call to the SetWindowPos function or 
1192                                          * another window-management function. 
1193                                          */
1194                                 case WM_SETFOCUS:
1195                                         /* The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus. */
1196                                 case WM_ENTERSIZEMOVE:
1197                                         /* The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving 
1198                                          * or sizing modal loop. The window enters the moving or sizing modal loop when the user 
1199                                          * clicks the window's title bar or sizing border, or when the window passes the 
1200                                          * WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the 
1201                                          * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when 
1202                                          * DefWindowProc returns. 
1203                                          */
1204                                         break;
1205                                                                         ////////////////////////////////////////////////////////////////////////
1206                                 // Other events
1207                                 ////////////////////////////////////////////////////////////////////////
1208                                 case WM_GETTEXT:
1209                                         /* An application sends a WM_GETTEXT message to copy the text that 
1210                                          * corresponds to a window into a buffer provided by the caller. 
1211                                          */
1212                                 case WM_ACTIVATEAPP:
1213                                         /* The WM_ACTIVATEAPP message is sent when a window belonging to a 
1214                                          * different application than the active window is about to be activated.
1215                                          * The message is sent to the application whose window is being activated
1216                                          * and to the application whose window is being deactivated. 
1217                                          */
1218                                 case WM_TIMER:
1219                                         /* The WIN32 docs say:
1220                                          * The WM_TIMER message is posted to the installing thread's message queue
1221                                          * when a timer expires. You can process the message by providing a WM_TIMER
1222                                          * case in the window procedure. Otherwise, the default window procedure will
1223                                          * call the TimerProc callback function specified in the call to the SetTimer
1224                                          * function used to install the timer. 
1225                                          *
1226                                          * In GHOST, we let DefWindowProc call the timer callback.
1227                                          */
1228                                         break;
1229                         }
1230                 }
1231                 else {
1232                         // Event found for a window before the pointer to the class has been set.
1233                         GHOST_PRINT("GHOST_SystemWin32::wndProc: GHOST window event before creation\n")
1234                         /* These are events we typically miss at this point:
1235                            WM_GETMINMAXINFO     0x24
1236                            WM_NCCREATE                  0x81
1237                            WM_NCCALCSIZE                0x83
1238                            WM_CREATE                    0x01
1239                            We let DefWindowProc do the work.
1240                         */
1241                 }
1242         }
1243         else {
1244                 // Events without valid hwnd
1245                 GHOST_PRINT("GHOST_SystemWin32::wndProc: event without window\n")
1246         }
1247
1248         if (event) {
1249                 system->pushEvent(event);
1250                 eventHandled = true;
1251         }
1252
1253         if (!eventHandled)
1254                 lResult = ::DefWindowProcW(hwnd, msg, wParam, lParam);
1255
1256         return lResult;
1257 }
1258
1259 GHOST_TUns8* GHOST_SystemWin32::getClipboard(bool selection) const 
1260 {
1261         char *temp_buff;
1262         
1263         if ( IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL) ) {
1264                 wchar_t *buffer;
1265                 HANDLE hData = GetClipboardData( CF_UNICODETEXT );
1266                 if (hData == NULL) {
1267                         CloseClipboard();
1268                         return NULL;
1269                 }
1270                 buffer = (wchar_t*)GlobalLock( hData );
1271                 if (!buffer) {
1272                         CloseClipboard();
1273                         return NULL;
1274                 }
1275                 
1276                 temp_buff = alloc_utf_8_from_16(buffer,0);
1277                 
1278                 /* Buffer mustn't be accessed after CloseClipboard
1279                    it would like accessing free-d memory */
1280                 GlobalUnlock( hData );
1281                 CloseClipboard();
1282                 
1283                 return (GHOST_TUns8*)temp_buff;
1284         } else if ( IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL) ) {
1285                 char *buffer;
1286                 size_t len = 0;
1287                 HANDLE hData = GetClipboardData( CF_TEXT );
1288                 if (hData == NULL) {
1289                         CloseClipboard();
1290                         return NULL;
1291                 }
1292                 buffer = (char*)GlobalLock( hData );
1293                 if (!buffer) {
1294                         CloseClipboard();
1295                         return NULL;
1296                 }
1297                 
1298                 len = strlen(buffer);
1299                 temp_buff = (char*) malloc(len+1);
1300                 strncpy(temp_buff, buffer, len);
1301                 temp_buff[len] = '\0';
1302                 
1303                 /* Buffer mustn't be accessed after CloseClipboard
1304                    it would like accessing free-d memory */
1305                 GlobalUnlock( hData );
1306                 CloseClipboard();
1307                 
1308                 return (GHOST_TUns8*)temp_buff;
1309         } else {
1310                 return NULL;
1311         }
1312 }
1313
1314 void GHOST_SystemWin32::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1315 {
1316         if(selection) {return;} // for copying the selection, used on X11
1317
1318         if(OpenClipboard(NULL)) {
1319                 HLOCAL clipbuffer;
1320                 wchar_t *data;
1321                 
1322                 if (buffer) {
1323                         size_t len = count_utf_16_from_8(buffer);
1324                         EmptyClipboard();
1325                         
1326                         clipbuffer = LocalAlloc(LMEM_FIXED,sizeof(wchar_t) * len);
1327                         data = (wchar_t*)GlobalLock(clipbuffer);
1328
1329                         conv_utf_8_to_16(buffer, data, len);
1330
1331                         LocalUnlock(clipbuffer);
1332                         SetClipboardData(CF_UNICODETEXT,clipbuffer);
1333                 }
1334                 CloseClipboard();
1335         } else {
1336                 return;
1337         }
1338 }
1339
1340 int GHOST_SystemWin32::toggleConsole(int action)
1341 {
1342         switch(action)
1343         {
1344                 case 3: //hide if no console
1345                         {
1346                                 DWORD sp = GetCurrentProcessId();
1347                                 HANDLE ptree = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
1348                                 PROCESSENTRY32 e = {0}; e.dwSize = sizeof(PROCESSENTRY32);
1349                                 
1350                                 if( Process32First(ptree, &e)) {
1351                                         do { //Searches for Blender's PROCESSENTRY32
1352                                                         if (e.th32ProcessID == sp) {
1353                                                                 sp = e.th32ParentProcessID;
1354                                                                 Process32First(ptree, &e);
1355                                                                         do { //Got parent id, searches for its PROCESSENTRY32
1356                                                                                 if (e.th32ProcessID == sp) {
1357                                                                                         if(strcmp("explorer.exe",e.szExeFile)==0)
1358                                                                                         { //If explorer, hide cmd
1359                                                                                                 ShowWindow(GetConsoleWindow(),SW_HIDE);
1360                                                                                                 m_consoleStatus = 0;
1361                                                                                         }
1362                                                                                         break;
1363                                                                                 }
1364
1365                                                                         } while( Process32Next(ptree, &e));
1366                                                                 break;
1367                                                         }
1368                                         } while( Process32Next(ptree, &e));
1369                                 }
1370
1371                                 CloseHandle(ptree);
1372                                 break;
1373                         }
1374                 case 0: //hide
1375                         ShowWindow(GetConsoleWindow(),SW_HIDE);
1376                         m_consoleStatus = 0;
1377                         break;
1378                 case 1: //show
1379                         ShowWindow(GetConsoleWindow(),SW_SHOW);
1380                         m_consoleStatus = 1;
1381                         break;
1382                 case 2: //toggle
1383                         ShowWindow(GetConsoleWindow(),m_consoleStatus?SW_HIDE:SW_SHOW);
1384                         m_consoleStatus=!m_consoleStatus;
1385                         break;
1386
1387         };
1388
1389
1390         return m_consoleStatus;
1391 }
1392
1393 int GHOST_SystemWin32::confirmQuit(GHOST_IWindow * window) const
1394 {
1395         return (MessageBox(window ? ((GHOST_WindowWin32*)window)->getHWND() : 0, "Some changes have not been saved.\nDo you really want to quit ?",
1396                         "Exit Blender", MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST) == IDOK);
1397 }