Ghost Context Refactor
[blender-staging.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  * \author      Maarten Gribnau
32  */
33
34 #ifdef WITH_GHOST_DEBUG
35 #  include <iostream>
36 #endif
37
38 #include <stdio.h> // [mce] temporary debug, remove soon!
39
40 #include "GHOST_SystemWin32.h"
41 #include "GHOST_EventDragnDrop.h"
42
43 #ifndef _WIN32_IE
44 #  define _WIN32_IE 0x0501 /* shipped before XP, so doesn't impose additional requirements */
45 #endif
46
47 #include <shlobj.h>
48 #include <tlhelp32.h>
49 #include <Psapi.h>
50 #include <windowsx.h>
51
52 #include "utfconv.h"
53
54 #include "GHOST_DisplayManagerWin32.h"
55 #include "GHOST_EventButton.h"
56 #include "GHOST_EventCursor.h"
57 #include "GHOST_EventKey.h"
58 #include "GHOST_EventWheel.h"
59 #include "GHOST_TimerTask.h"
60 #include "GHOST_TimerManager.h"
61 #include "GHOST_WindowManager.h"
62 #include "GHOST_WindowWin32.h"
63
64 #ifdef WITH_INPUT_NDOF
65 #include "GHOST_NDOFManagerWin32.h"
66 #endif
67
68 // Key code values not found in winuser.h
69 #ifndef VK_MINUS
70 #define VK_MINUS 0xBD
71 #endif // VK_MINUS
72 #ifndef VK_SEMICOLON
73 #define VK_SEMICOLON 0xBA
74 #endif // VK_SEMICOLON
75 #ifndef VK_PERIOD
76 #define VK_PERIOD 0xBE
77 #endif // VK_PERIOD
78 #ifndef VK_COMMA
79 #define VK_COMMA 0xBC
80 #endif // VK_COMMA
81 #ifndef VK_QUOTE
82 #define VK_QUOTE 0xDE
83 #endif // VK_QUOTE
84 #ifndef VK_BACK_QUOTE
85 #define VK_BACK_QUOTE 0xC0
86 #endif // VK_BACK_QUOTE
87 #ifndef VK_SLASH
88 #define VK_SLASH 0xBF
89 #endif // VK_SLASH
90 #ifndef VK_BACK_SLASH
91 #define VK_BACK_SLASH 0xDC
92 #endif // VK_BACK_SLASH
93 #ifndef VK_EQUALS
94 #define VK_EQUALS 0xBB
95 #endif // VK_EQUALS
96 #ifndef VK_OPEN_BRACKET
97 #define VK_OPEN_BRACKET 0xDB
98 #endif // VK_OPEN_BRACKET
99 #ifndef VK_CLOSE_BRACKET
100 #define VK_CLOSE_BRACKET 0xDD
101 #endif // VK_CLOSE_BRACKET
102 #ifndef VK_GR_LESS
103 #define VK_GR_LESS 0xE2
104 #endif // VK_GR_LESS
105
106 #ifndef VK_MEDIA_NEXT_TRACK
107 #define VK_MEDIA_NEXT_TRACK 0xB0
108 #endif // VK_MEDIA_NEXT_TRACK
109 #ifndef VK_MEDIA_PREV_TRACK
110 #define VK_MEDIA_PREV_TRACK 0xB1
111 #endif // VK_MEDIA_PREV_TRACK
112 #ifndef VK_MEDIA_STOP
113 #define VK_MEDIA_STOP 0xB2
114 #endif // VK_MEDIA_STOP
115 #ifndef VK_MEDIA_PLAY_PAUSE
116 #define VK_MEDIA_PLAY_PAUSE 0xB3
117 #endif // VK_MEDIA_PLAY_PAUSE
118
119 /* Workaround for some laptop touchpads, some of which seems to
120  * have driver issues which makes it so window function receives
121  * the message, but PeekMessage doesn't pick those messages for
122  * some reason.
123  *
124  * We send a dummy WM_USER message to force PeekMessage to receive
125  * something, making it so blender's window manager sees the new
126  * messages coming in.
127  */
128 #define BROKEN_PEEK_TOUCHPAD
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 void GHOST_SystemWin32::getAllDisplayDimensions(GHOST_TUns32 &width, GHOST_TUns32 &height) const
224 {
225         width = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
226         height = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
227 }
228
229 GHOST_IWindow *GHOST_SystemWin32::createWindow(
230         const STR_String &title,
231         GHOST_TInt32 left, GHOST_TInt32 top,
232         GHOST_TUns32 width, GHOST_TUns32 height,
233         GHOST_TWindowState state, GHOST_TDrawingContextType type,
234         bool wantStereoVisual,
235         const bool exclusive,
236         const GHOST_TUns16 wantNumOfAASamples,
237         const GHOST_TEmbedderWindowID parentWindow)
238 {
239         GHOST_Window *window =
240                 new GHOST_WindowWin32(
241                         this,
242                         title,
243                         left,
244                         top,
245                         width,
246                         height,
247                         state,
248                         type,
249                         wantStereoVisual,
250                         wantNumOfAASamples,
251                         parentWindow);
252
253         if (window->getValid()) {
254                 // Store the pointer to the window
255                 m_windowManager->addWindow(window);
256                 m_windowManager->setActiveWindow(window);
257         }
258         else {
259                 GHOST_PRINT("GHOST_SystemWin32::createWindow(): window invalid\n");
260                 delete window;
261                 window = 0;
262         }
263
264         return window;
265 }
266
267
268 bool GHOST_SystemWin32::processEvents(bool waitForEvent)
269 {
270         MSG msg;
271         bool anyProcessed = false;
272
273         do {
274                 GHOST_TimerManager *timerMgr = getTimerManager();
275
276                 if (waitForEvent && !::PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE)) {
277 #if 1
278                         ::Sleep(1);
279 #else
280                         GHOST_TUns64 next = timerMgr->nextFireTime();
281                         GHOST_TInt64 maxSleep = next - getMilliSeconds();
282                         
283                         if (next == GHOST_kFireTimeNever) {
284                                 ::WaitMessage();
285                         }
286                         else if (maxSleep >= 0.0) {
287                                 ::SetTimer(NULL, 0, maxSleep, NULL);
288                                 ::WaitMessage();
289                                 ::KillTimer(NULL, 0);
290                         }
291 #endif
292                 }
293
294                 if (timerMgr->fireTimers(getMilliSeconds())) {
295                         anyProcessed = true;
296                 }
297
298                 // Process all the events waiting for us
299                 while (::PeekMessageW(&msg, 0, 0, 0, PM_REMOVE) != 0) {
300                         // TranslateMessage doesn't alter the message, and doesn't change our raw keyboard data.
301                         // Needed for MapVirtualKey or if we ever need to get chars from wm_ime_char or similar.
302                         ::TranslateMessage(&msg);
303                         ::DispatchMessageW(&msg);
304                         anyProcessed = true;
305                 }
306         } while (waitForEvent && !anyProcessed);
307
308         return anyProcessed;
309 }
310
311
312 GHOST_TSuccess GHOST_SystemWin32::getCursorPosition(GHOST_TInt32 &x, GHOST_TInt32 &y) const
313 {
314         POINT point;
315         if (::GetCursorPos(&point)) {
316                 x = point.x;
317                 y = point.y;
318                 return GHOST_kSuccess;
319         }
320         return GHOST_kFailure;
321 }
322
323
324 GHOST_TSuccess GHOST_SystemWin32::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y)
325 {
326         if (!::GetActiveWindow())
327                 return GHOST_kFailure;
328         return ::SetCursorPos(x, y) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
329 }
330
331
332 GHOST_TSuccess GHOST_SystemWin32::getModifierKeys(GHOST_ModifierKeys &keys) const
333 {
334         bool down = HIBYTE(::GetKeyState(VK_LSHIFT)) != 0;
335         keys.set(GHOST_kModifierKeyLeftShift, down);
336         down = HIBYTE(::GetKeyState(VK_RSHIFT)) != 0;
337         keys.set(GHOST_kModifierKeyRightShift, down);
338         
339         down = HIBYTE(::GetKeyState(VK_LMENU)) != 0;
340         keys.set(GHOST_kModifierKeyLeftAlt, down);
341         down = HIBYTE(::GetKeyState(VK_RMENU)) != 0;
342         keys.set(GHOST_kModifierKeyRightAlt, down);
343         
344         down = HIBYTE(::GetKeyState(VK_LCONTROL)) != 0;
345         keys.set(GHOST_kModifierKeyLeftControl, down);
346         down = HIBYTE(::GetKeyState(VK_RCONTROL)) != 0;
347         keys.set(GHOST_kModifierKeyRightControl, down);
348         
349         bool lwindown = HIBYTE(::GetKeyState(VK_LWIN)) != 0;
350         bool rwindown = HIBYTE(::GetKeyState(VK_RWIN)) != 0;
351         if (lwindown || rwindown)
352                 keys.set(GHOST_kModifierKeyOS, true);
353         else
354                 keys.set(GHOST_kModifierKeyOS, false);
355         return GHOST_kSuccess;
356 }
357
358
359 GHOST_TSuccess GHOST_SystemWin32::getButtons(GHOST_Buttons &buttons) const
360 {
361         /* Check for swapped buttons (left-handed mouse buttons)
362          * GetAsyncKeyState() will give back the state of the physical mouse buttons.
363          */
364         bool swapped = ::GetSystemMetrics(SM_SWAPBUTTON) == TRUE;
365
366         bool down = HIBYTE(::GetKeyState(VK_LBUTTON)) != 0;
367         buttons.set(swapped ? GHOST_kButtonMaskRight : GHOST_kButtonMaskLeft, down);
368
369         down = HIBYTE(::GetKeyState(VK_MBUTTON)) != 0;
370         buttons.set(GHOST_kButtonMaskMiddle, down);
371
372         down = HIBYTE(::GetKeyState(VK_RBUTTON)) != 0;
373         buttons.set(swapped ? GHOST_kButtonMaskLeft : GHOST_kButtonMaskRight, down);
374         return GHOST_kSuccess;
375 }
376
377
378 GHOST_TSuccess GHOST_SystemWin32::init()
379 {
380         GHOST_TSuccess success = GHOST_System::init();
381         
382         /* Disable scaling on high DPI displays on Vista */
383         HMODULE
384             user32 = ::LoadLibraryA("user32.dll");
385         typedef BOOL (WINAPI * LPFNSETPROCESSDPIAWARE)();
386         LPFNSETPROCESSDPIAWARE SetProcessDPIAware =
387             (LPFNSETPROCESSDPIAWARE)GetProcAddress(user32, "SetProcessDPIAware");
388         if (SetProcessDPIAware)
389                 SetProcessDPIAware();
390         FreeLibrary(user32);
391         initRawInput();
392
393         // Determine whether this system has a high frequency performance counter. */
394         m_hasPerformanceCounter = ::QueryPerformanceFrequency((LARGE_INTEGER *)&m_freq) == TRUE;
395         if (m_hasPerformanceCounter) {
396                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer available\n");
397                 ::QueryPerformanceCounter((LARGE_INTEGER *)&m_start);
398         }
399         else {
400                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer not available\n");
401         }
402
403         if (success) {
404                 WNDCLASSW wc = {0};
405                 wc.style = CS_HREDRAW | CS_VREDRAW;
406                 wc.lpfnWndProc = s_wndProc;
407                 wc.cbClsExtra = 0;
408                 wc.cbWndExtra = 0;
409                 wc.hInstance = ::GetModuleHandle(0);
410                 wc.hIcon = ::LoadIcon(wc.hInstance, "APPICON");
411                 
412                 if (!wc.hIcon) {
413                         ::LoadIcon(NULL, IDI_APPLICATION);
414                 }
415                 wc.hCursor = ::LoadCursor(0, IDC_ARROW);
416                 wc.hbrBackground = 0;
417                 wc.lpszMenuName = 0;
418                 wc.lpszClassName = L"GHOST_WindowClass";
419
420                 // Use RegisterClassEx for setting small icon
421                 if (::RegisterClassW(&wc) == 0) {
422                         success = GHOST_kFailure;
423                 }
424         }
425         
426         return success;
427 }
428
429
430 GHOST_TSuccess GHOST_SystemWin32::exit()
431 {
432         return GHOST_System::exit();
433 }
434
435 GHOST_TKey GHOST_SystemWin32::hardKey(GHOST_IWindow *window, RAWINPUT const &raw, int *keyDown, char *vk)
436 {
437         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
438         GHOST_TKey key = GHOST_kKeyUnknown;
439         GHOST_ModifierKeys modifiers;
440         system->retrieveModifierKeys(modifiers);
441
442         // RI_KEY_BREAK doesn't work for sticky keys release, so we also
443         // check for the up message
444         unsigned int msg = raw.data.keyboard.Message;
445         *keyDown = !(raw.data.keyboard.Flags & RI_KEY_BREAK) && msg != WM_KEYUP && msg != WM_SYSKEYUP;
446
447         key = this->convertKey(window, raw.data.keyboard.VKey, raw.data.keyboard.MakeCode, (raw.data.keyboard.Flags & (RI_KEY_E1 | RI_KEY_E0)));
448         
449         // extra handling of modifier keys: don't send repeats out from GHOST
450         if (key >= GHOST_kKeyLeftShift && key <= GHOST_kKeyRightAlt) {
451                 bool changed = false;
452                 GHOST_TModifierKeyMask modifier;
453                 switch (key) {
454                         case GHOST_kKeyLeftShift:
455                         {
456                                 changed = (modifiers.get(GHOST_kModifierKeyLeftShift) != (bool)*keyDown);
457                                 modifier = GHOST_kModifierKeyLeftShift;
458                                 break;
459                         }
460                         case GHOST_kKeyRightShift:
461                         {
462                                 changed = (modifiers.get(GHOST_kModifierKeyRightShift) != (bool)*keyDown);
463                                 modifier = GHOST_kModifierKeyRightShift;
464                                 break;
465                         }
466                         case GHOST_kKeyLeftControl:
467                         {
468                                 changed = (modifiers.get(GHOST_kModifierKeyLeftControl) != (bool)*keyDown);
469                                 modifier = GHOST_kModifierKeyLeftControl;
470                                 break;
471                         }
472                         case GHOST_kKeyRightControl:
473                         {
474                                 changed = (modifiers.get(GHOST_kModifierKeyRightControl) != (bool)*keyDown);
475                                 modifier = GHOST_kModifierKeyRightControl;
476                                 break;
477                         }
478                         case GHOST_kKeyLeftAlt:
479                         {
480                                 changed = (modifiers.get(GHOST_kModifierKeyLeftAlt) != (bool)*keyDown);
481                                 modifier = GHOST_kModifierKeyLeftAlt;
482                                 break;
483                         }
484                         case GHOST_kKeyRightAlt:
485                         {
486                                 changed = (modifiers.get(GHOST_kModifierKeyRightAlt) != (bool)*keyDown);
487                                 modifier = GHOST_kModifierKeyRightAlt;
488                                 break;
489                         }
490                         default:
491                                 break;
492                 }
493                 
494                 if (changed) {
495                         modifiers.set(modifier, (bool)*keyDown);
496                         system->storeModifierKeys(modifiers);
497                 }
498                 else {
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                                 /* Check single shift presses */
604                                 if (scanCode == 0x36) {
605                                         key = GHOST_kKeyRightShift;
606                                 }
607                                 else if (scanCode == 0x2a) {
608                                         key = GHOST_kKeyLeftShift;
609                                 }
610                                 else {
611                                         /* Must be a combination SHIFT (Left or Right) + a Key
612                                          * Ignore this as the next message will contain
613                                          * the desired "Key" */
614                                         key = GHOST_kKeyUnknown;
615                                 }
616                                 break;
617                         case VK_CONTROL:
618                                 key = (extend) ? GHOST_kKeyRightControl : GHOST_kKeyLeftControl;
619                                 break;
620                         case VK_MENU:
621                                 key = (extend) ? GHOST_kKeyRightAlt : GHOST_kKeyLeftAlt;
622                                 break;
623                         case VK_LWIN:
624                         case VK_RWIN:
625                                 key = GHOST_kKeyOS;
626                                 break;
627                         case VK_NUMLOCK: key = GHOST_kKeyNumLock; break;
628                         case VK_SCROLL: key = GHOST_kKeyScrollLock; break;
629                         case VK_CAPITAL: key = GHOST_kKeyCapsLock; break;
630                         case VK_OEM_8:
631                                 key = ((GHOST_SystemWin32 *)getSystem())->processSpecialKey(window, vKey, scanCode);
632                                 break;
633                         case VK_MEDIA_PLAY_PAUSE: key = GHOST_kKeyMediaPlay; break;
634                         case VK_MEDIA_STOP: key = GHOST_kKeyMediaStop; break;
635                         case VK_MEDIA_PREV_TRACK: key = GHOST_kKeyMediaFirst; break;
636                         case VK_MEDIA_NEXT_TRACK: key = GHOST_kKeyMediaLast; break;
637                         default:
638                                 key = GHOST_kKeyUnknown;
639                                 break;
640                 }
641         }
642         
643         return key;
644 }
645
646 GHOST_EventButton *GHOST_SystemWin32::processButtonEvent(
647         GHOST_TEventType type,
648         GHOST_IWindow *window,
649         GHOST_TButtonMask mask)
650 {
651         return new GHOST_EventButton(getSystem()->getMilliSeconds(), type, window, mask);
652 }
653
654
655 GHOST_EventCursor *GHOST_SystemWin32::processCursorEvent(GHOST_TEventType type, GHOST_IWindow *Iwindow)
656 {
657         GHOST_TInt32 x_screen, y_screen;
658         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *) getSystem();
659         GHOST_WindowWin32 *window = (GHOST_WindowWin32 *) Iwindow;
660         
661         system->getCursorPosition(x_screen, y_screen);
662
663         /* TODO: CHECK IF THIS IS A TABLET EVENT */
664         bool is_tablet = false;
665
666         if (is_tablet == false && window->getCursorGrabModeIsWarp()) {
667                 GHOST_TInt32 x_new = x_screen;
668                 GHOST_TInt32 y_new = y_screen;
669                 GHOST_TInt32 x_accum, y_accum;
670                 GHOST_Rect bounds;
671
672                 /* fallback to window bounds */
673                 if (window->getCursorGrabBounds(bounds) == GHOST_kFailure) {
674                         window->getClientBounds(bounds);
675                 }
676
677                 /* could also clamp to screen bounds
678                  * wrap with a window outside the view will fail atm  */
679
680                 bounds.wrapPoint(x_new, y_new, 2); /* offset of one incase blender is at screen bounds */
681
682                 window->getCursorGrabAccum(x_accum, y_accum);
683                 if (x_new != x_screen || y_new != y_screen) {
684                         /* when wrapping we don't need to add an event because the
685                          * setCursorPosition call will cause a new event after */
686                         system->setCursorPosition(x_new, y_new); /* wrap */
687                         window->setCursorGrabAccum(x_accum + (x_screen - x_new), y_accum + (y_screen - y_new));
688                 }
689                 else {
690                         return new GHOST_EventCursor(system->getMilliSeconds(),
691                                                      GHOST_kEventCursorMove,
692                                                      window,
693                                                      x_screen + x_accum,
694                                                      y_screen + y_accum
695                                                      );
696                 }
697
698         }
699         else {
700                 return new GHOST_EventCursor(system->getMilliSeconds(),
701                                              GHOST_kEventCursorMove,
702                                              window,
703                                              x_screen,
704                                              y_screen
705                                              );
706         }
707         return NULL;
708 }
709
710
711 GHOST_EventWheel *GHOST_SystemWin32::processWheelEvent(GHOST_IWindow *window, WPARAM wParam, LPARAM lParam)
712 {
713         // short fwKeys = LOWORD(wParam);                       // key flags
714         int zDelta = (short) HIWORD(wParam);    // wheel rotation
715         
716         // zDelta /= WHEEL_DELTA;
717         // temporary fix below: microsoft now has added more precision, making the above division not work
718         if (zDelta <= 0) zDelta = -1; else zDelta = 1;
719         
720         // short xPos = (short) LOWORD(lParam); // horizontal position of pointer
721         // short yPos = (short) HIWORD(lParam); // vertical position of pointer
722         return new GHOST_EventWheel(getSystem()->getMilliSeconds(), window, zDelta);
723 }
724
725
726 GHOST_EventKey *GHOST_SystemWin32::processKeyEvent(GHOST_IWindow *window, RAWINPUT const &raw)
727 {
728         int keyDown = 0;
729         char vk;
730         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
731         GHOST_TKey key = system->hardKey(window, raw, &keyDown, &vk);
732         GHOST_EventKey *event;
733
734         if (key != GHOST_kKeyUnknown) {
735                 char utf8_char[6] = {0};
736                 char ascii = 0;
737
738                 wchar_t utf16[3] = {0};
739                 BYTE state[256] = {0};
740                 int r;
741                 GetKeyboardState((PBYTE)state);
742
743                 // don't call ToUnicodeEx on dead keys as it clears the buffer and so won't allow diacritical composition.
744                 if (MapVirtualKeyW(vk, 2) != 0) {
745                         // todo: ToUnicodeEx can respond with up to 4 utf16 chars (only 2 here). Could be up to 24 utf8 bytes.
746                         if ((r = ToUnicodeEx(vk, raw.data.keyboard.MakeCode, state, utf16, 2, 0, system->m_keylayout))) {
747                                 if ((r > 0 && r < 3)) {
748                                         utf16[r] = 0;
749                                         conv_utf_16_to_8(utf16, utf8_char, 6);
750                                 }
751                                 else if (r == -1) {
752                                         utf8_char[0] = '\0';
753                                 }
754                         }
755                 }
756
757                 if (!keyDown) {
758                         utf8_char[0] = '\0';
759                         ascii = '\0';
760                 }
761                 else {
762                         ascii = utf8_char[0] & 0x80 ? '?' : utf8_char[0];
763                 }
764
765                 event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, key, ascii, utf8_char);
766                 
767 #ifdef GHOST_DEBUG
768                 std::cout << ascii << std::endl;
769 #endif
770         }
771         else {
772                 event = 0;
773         }
774         return event;
775 }
776
777
778 GHOST_Event *GHOST_SystemWin32::processWindowEvent(GHOST_TEventType type, GHOST_IWindow *window)
779 {
780         GHOST_System *system = (GHOST_System *)getSystem();
781
782         if (type == GHOST_kEventWindowActivate) {
783                 system->getWindowManager()->setActiveWindow(window);
784                 ((GHOST_WindowWin32 *)window)->bringTabletContextToFront();
785         }
786
787         return new GHOST_Event(system->getMilliSeconds(), type, window);
788 }
789
790 GHOST_TSuccess GHOST_SystemWin32::pushDragDropEvent(
791         GHOST_TEventType eventType,
792         GHOST_TDragnDropTypes draggedObjectType,
793         GHOST_IWindow *window,
794         int mouseX, int mouseY,
795         void *data)
796 {
797         GHOST_SystemWin32 *system = ((GHOST_SystemWin32 *)getSystem());
798         return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
799                                                           eventType,
800                                                           draggedObjectType,
801                                                           window, mouseX, mouseY, data)
802                                  );
803 }
804
805 void GHOST_SystemWin32::processMinMaxInfo(MINMAXINFO *minmax)
806 {
807         minmax->ptMinTrackSize.x = 320;
808         minmax->ptMinTrackSize.y = 240;
809 }
810
811 #ifdef WITH_INPUT_NDOF
812 bool GHOST_SystemWin32::processNDOF(RAWINPUT const &raw)
813 {
814         bool eventSent = false;
815         GHOST_TUns64 now = getMilliSeconds();
816
817         static bool firstEvent = true;
818         if (firstEvent) { // determine exactly which device is plugged in
819                 RID_DEVICE_INFO info;
820                 unsigned infoSize = sizeof(RID_DEVICE_INFO);
821                 info.cbSize = infoSize;
822
823                 GetRawInputDeviceInfo(raw.header.hDevice, RIDI_DEVICEINFO, &info, &infoSize);
824                 if (info.dwType == RIM_TYPEHID)
825                         m_ndofManager->setDevice(info.hid.dwVendorId, info.hid.dwProductId);
826                 else
827                         puts("<!> not a HID device... mouse/kb perhaps?");
828
829                 firstEvent = false;
830         }
831
832         // The NDOF manager sends button changes immediately, and *pretends* to
833         // send motion. Mark as 'sent' so motion will always get dispatched.
834         eventSent = true;
835
836 #if defined(_MSC_VER) || defined(FREE_WINDOWS64)
837         // using Microsoft compiler & header files
838         // they invented the RawInput API, so this version is (probably) correct.
839         // MinGW64 also works fine with this
840         BYTE const *data = raw.data.hid.bRawData;
841         // struct RAWHID {
842         // DWORD dwSizeHid;
843         // DWORD dwCount;
844         // BYTE  bRawData[1];
845         // };
846 #else
847         // MinGW's definition (below) doesn't agree, so we need a slight
848         // workaround until it's fixed
849         BYTE const *data = &raw.data.hid.bRawData;
850         // struct RAWHID {
851         // DWORD dwSizeHid;
852         // DWORD dwCount;
853         // BYTE bRawData; // <== isn't this s'posed to be a BYTE*?
854         // };
855 #endif
856
857         BYTE packetType = data[0];
858         switch (packetType) {
859                 case 1: // translation
860                 {
861                         const short *axis = (short *)(data + 1);
862                         // massage into blender view coords (same goes for rotation)
863                         const short t[3] = {axis[0], -axis[2], axis[1]};
864                         m_ndofManager->updateTranslation(t, now);
865
866                         if (raw.data.hid.dwSizeHid == 13) {
867                                 // this report also includes rotation
868                                 const short r[3] = {-axis[3], axis[5], -axis[4]};
869                                 m_ndofManager->updateRotation(r, now);
870
871                                 // I've never gotten one of these, has anyone else?
872                                 puts("ndof: combined T + R");
873                         }
874                         break;
875                 }
876                 case 2: // rotation
877                 {
878                         const short *axis = (short *)(data + 1);
879                         const short r[3] = {-axis[0], axis[2], -axis[1]};
880                         m_ndofManager->updateRotation(r, now);
881                         break;
882                 }
883                 case 3: // buttons
884                 {
885                         int button_bits;
886                         memcpy(&button_bits, data + 1, sizeof(button_bits));
887                         m_ndofManager->updateButtons(button_bits, now);
888                         break;
889                 }
890         }
891         return eventSent;
892 }
893 #endif // WITH_INPUT_NDOF
894
895 LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
896 {
897         GHOST_Event *event = 0;
898         bool eventHandled = false;
899
900         LRESULT lResult = 0;
901         GHOST_SystemWin32 *system = ((GHOST_SystemWin32 *)getSystem());
902         GHOST_ASSERT(system, "GHOST_SystemWin32::s_wndProc(): system not initialized");
903
904         if (hwnd) {
905                 GHOST_WindowWin32 *window = (GHOST_WindowWin32 *)::GetWindowLongPtr(hwnd, GWLP_USERDATA);
906                 if (window) {
907                         switch (msg) {
908                                 // we need to check if new key layout has AltGr
909                                 case WM_INPUTLANGCHANGE:
910                                         system->handleKeyboardChange();
911                                         break;
912                                 ////////////////////////////////////////////////////////////////////////
913                                 // Keyboard events, processed
914                                 ////////////////////////////////////////////////////////////////////////
915                                 case WM_INPUT:
916                                 {
917                                         // check WM_INPUT from input sink when ghost window is not in the foreground
918                                         if (wParam == RIM_INPUTSINK) {
919                                                 if (GetFocus() != hwnd) // WM_INPUT message not for this window
920                                                         return 0;
921                                         } //else wParam == RIM_INPUT
922
923                                         RAWINPUT raw;
924                                         RAWINPUT *raw_ptr = &raw;
925                                         UINT rawSize = sizeof(RAWINPUT);
926
927                                         GetRawInputData((HRAWINPUT)lParam, RID_INPUT, raw_ptr, &rawSize, sizeof(RAWINPUTHEADER));
928
929                                         switch (raw.header.dwType) {
930                                                 case RIM_TYPEKEYBOARD:
931                                                         event = processKeyEvent(window, raw);
932                                                         if (!event) {
933                                                                 GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ");
934                                                                 GHOST_PRINT(msg);
935                                                                 GHOST_PRINT(" key ignored\n");
936                                                         }
937                                                         break;
938 #ifdef WITH_INPUT_NDOF
939                                                 case RIM_TYPEHID:
940                                                         if (system->processNDOF(raw))
941                                                                 eventHandled = true;
942                                                         break;
943 #endif
944                                         }
945                                         break;
946                                 }
947                                 ////////////////////////////////////////////////////////////////////////
948                                 // Keyboard events, ignored
949                                 ////////////////////////////////////////////////////////////////////////
950                                 case WM_KEYDOWN:
951                                 case WM_SYSKEYDOWN:
952                                 case WM_KEYUP:
953                                 case WM_SYSKEYUP:
954                                 /* These functions were replaced by WM_INPUT*/
955                                 case WM_CHAR:
956                                 /* The WM_CHAR message is posted to the window with the keyboard focus when
957                                  * a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR
958                                  * contains the character code of the key that was pressed.
959                                  */
960                                 case WM_DEADCHAR:
961                                         /* The WM_DEADCHAR message is posted to the window with the keyboard focus when a
962                                          * WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR 
963                                          * specifies a character code generated by a dead key. A dead key is a key that 
964                                          * generates a character, such as the umlaut (double-dot), that is combined with 
965                                          * another character to form a composite character. For example, the umlaut-O 
966                                          * character (Ö) is generated by typing the dead key for the umlaut character, and
967                                          * then typing the O key.
968                                          */
969                                         break;
970                                 case WM_SYSDEADCHAR:
971                                 /* The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when
972                                  * a WM_SYSKEYDOWN message is translated by the TranslateMessage function.
973                                  * WM_SYSDEADCHAR specifies the character code of a system dead key - that is,
974                                  * a dead key that is pressed while holding down the alt key.
975                                  */
976                                 case WM_SYSCHAR:
977                                         /* The WM_SYSCHAR message is sent to the window with the keyboard focus when 
978                                          * a WM_SYSCHAR message is translated by the TranslateMessage function. 
979                                          * WM_SYSCHAR specifies the character code of a dead key - that is, 
980                                          * a dead key that is pressed while holding down the alt key.
981                                          * To prevent the sound, DefWindowProc must be avoided by return
982                                          */
983                                         break;
984                                 case WM_SYSCOMMAND:
985                                         /* The WM_SYSCHAR message is sent to the window when system commands such as 
986                                          * maximize, minimize  or close the window are triggered. Also it is sent when ALT 
987                                          * button is press for menu. To prevent this we must return preventing DefWindowProc.
988                                          */
989                                         if (wParam == SC_KEYMENU) {
990                                                 eventHandled = true;
991                                         }
992                                         break;
993                                 ////////////////////////////////////////////////////////////////////////
994                                 // Tablet events, processed
995                                 ////////////////////////////////////////////////////////////////////////
996                                 case WT_PACKET:
997                                         ((GHOST_WindowWin32 *)window)->processWin32TabletEvent(wParam, lParam);
998                                         break;
999                                 case WT_CSRCHANGE:
1000                                 case WT_PROXIMITY:
1001                                         ((GHOST_WindowWin32 *)window)->processWin32TabletInitEvent();
1002                                         break;
1003                                 ////////////////////////////////////////////////////////////////////////
1004                                 // Mouse events, processed
1005                                 ////////////////////////////////////////////////////////////////////////
1006                                 case WM_LBUTTONDOWN:
1007                                         window->registerMouseClickEvent(0);
1008                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskLeft);
1009                                         break;
1010                                 case WM_MBUTTONDOWN:
1011                                         window->registerMouseClickEvent(0);
1012                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskMiddle);
1013                                         break;
1014                                 case WM_RBUTTONDOWN:
1015                                         window->registerMouseClickEvent(0);
1016                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskRight);
1017                                         break;
1018                                 case WM_XBUTTONDOWN:
1019                                         window->registerMouseClickEvent(0);
1020                                         if ((short) HIWORD(wParam) == XBUTTON1) {
1021                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton4);
1022                                         }
1023                                         else if ((short) HIWORD(wParam) == XBUTTON2) {
1024                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton5);
1025                                         }
1026                                         break;
1027                                 case WM_LBUTTONUP:
1028                                         window->registerMouseClickEvent(1);
1029                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskLeft);
1030                                         break;
1031                                 case WM_MBUTTONUP:
1032                                         window->registerMouseClickEvent(1);
1033                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskMiddle);
1034                                         break;
1035                                 case WM_RBUTTONUP:
1036                                         window->registerMouseClickEvent(1);
1037                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskRight);
1038                                         break;
1039                                 case WM_XBUTTONUP:
1040                                         window->registerMouseClickEvent(1);
1041                                         if ((short) HIWORD(wParam) == XBUTTON1) {
1042                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton4);
1043                                         }
1044                                         else if ((short) HIWORD(wParam) == XBUTTON2) {
1045                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton5);
1046                                         }
1047                                         break;
1048                                 case WM_MOUSEMOVE:
1049                                         event = processCursorEvent(GHOST_kEventCursorMove, window);
1050                                         break;
1051                                 case WM_MOUSEWHEEL:
1052                                 {
1053                                         /* The WM_MOUSEWHEEL message is sent to the focus window 
1054                                          * when the mouse wheel is rotated. The DefWindowProc 
1055                                          * function propagates the message to the window's parent.
1056                                          * There should be no internal forwarding of the message, 
1057                                          * since DefWindowProc propagates it up the parent chain 
1058                                          * until it finds a window that processes it.
1059                                          */
1060
1061                                         /* Get the winow under the mouse and send event to it's queue. */
1062                                         POINT mouse_pos = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
1063                                         HWND mouse_hwnd = WindowFromPoint(mouse_pos);
1064                                         GHOST_WindowWin32 *mouse_window = (GHOST_WindowWin32 *)::GetWindowLongPtr(mouse_hwnd, GWLP_USERDATA);
1065                                         if (mouse_window != NULL) {
1066                                                 event = processWheelEvent(mouse_window, wParam, lParam);
1067                                         }
1068                                         else {
1069                                                 /* If it happened so window under the mouse is not found (which i'm not
1070                                                  * really sure might happen), then we add event to the focused window
1071                                                  * in order to avoid some possible negative side effects.
1072                                                  *                                                    - sergey -
1073                                                  */
1074                                                 event = processWheelEvent(window, wParam, lParam);
1075                                         }
1076
1077 #ifdef BROKEN_PEEK_TOUCHPAD
1078                                         PostMessage(hwnd, WM_USER, 0, 0);
1079 #endif
1080                                         break;
1081                                 }
1082                                 case WM_SETCURSOR:
1083                                         /* The WM_SETCURSOR message is sent to a window if the mouse causes the cursor
1084                                          * to move within a window and mouse input is not captured.
1085                                          * This means we have to set the cursor shape every time the mouse moves!
1086                                          * The DefWindowProc function uses this message to set the cursor to an 
1087                                          * arrow if it is not in the client area.
1088                                          */
1089                                         if (LOWORD(lParam) == HTCLIENT) {
1090                                                 // Load the current cursor
1091                                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
1092                                                 // Bypass call to DefWindowProc
1093                                                 return 0;
1094                                         } 
1095                                         else {
1096                                                 // Outside of client area show standard cursor
1097                                                 window->loadCursor(true, GHOST_kStandardCursorDefault);
1098                                         }
1099                                         break;
1100
1101                                 ////////////////////////////////////////////////////////////////////////
1102                                 // Mouse events, ignored
1103                                 ////////////////////////////////////////////////////////////////////////
1104                                 case WM_NCMOUSEMOVE:
1105                                 /* The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved
1106                                  * within the nonclient area of the window. This message is posted to the window
1107                                  * that contains the cursor. If a window has captured the mouse, this message is not posted.
1108                                  */
1109                                 case WM_NCHITTEST:
1110                                         /* The WM_NCHITTEST message is sent to a window when the cursor moves, or 
1111                                          * when a mouse button is pressed or released. If the mouse is not captured, 
1112                                          * the message is sent to the window beneath the cursor. Otherwise, the message 
1113                                          * is sent to the window that has captured the mouse. 
1114                                          */
1115                                         break;
1116
1117                                 ////////////////////////////////////////////////////////////////////////
1118                                 // Window events, processed
1119                                 ////////////////////////////////////////////////////////////////////////
1120                                 case WM_CLOSE:
1121                                         /* The WM_CLOSE message is sent as a signal that a window or an application should terminate. */
1122                                         event = processWindowEvent(GHOST_kEventWindowClose, window);
1123                                         break;
1124                                 case WM_ACTIVATE:
1125                                         /* The WM_ACTIVATE message is sent to both the window being activated and the window being 
1126                                          * deactivated. If the windows use the same input queue, the message is sent synchronously, 
1127                                          * first to the window procedure of the top-level window being deactivated, then to the window
1128                                          * procedure of the top-level window being activated. If the windows use different input queues,
1129                                          * the message is sent asynchronously, so the window is activated immediately. 
1130                                          */
1131                                 {
1132                                         GHOST_ModifierKeys modifiers;
1133                                         modifiers.clear();
1134                                         system->storeModifierKeys(modifiers);
1135                                         event = processWindowEvent(LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
1136                                         /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
1137                                          * will not be dispatched to OUR active window if we minimize one of OUR windows. */
1138                                         if (LOWORD(wParam) == WA_INACTIVE)
1139                                                 window->lostMouseCapture();
1140
1141                                         lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
1142                                         break;
1143                                 }
1144                                 case WM_ENTERSIZEMOVE:
1145                                         /* The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving 
1146                                          * or sizing modal loop. The window enters the moving or sizing modal loop when the user 
1147                                          * clicks the window's title bar or sizing border, or when the window passes the 
1148                                          * WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the 
1149                                          * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when 
1150                                          * DefWindowProc returns. 
1151                                          */
1152                                         window->m_inLiveResize = 1;
1153                                         break;
1154                                 case WM_EXITSIZEMOVE:
1155                                         window->m_inLiveResize = 0;
1156                                         break;
1157                                 case WM_PAINT:
1158                                         /* An application sends the WM_PAINT message when the system or another application 
1159                                          * makes a request to paint a portion of an application's window. The message is sent
1160                                          * when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage 
1161                                          * function when the application obtains a WM_PAINT message by using the GetMessage or 
1162                                          * PeekMessage function. 
1163                                          */
1164                                         if (!window->m_inLiveResize) {
1165                                                 event = processWindowEvent(GHOST_kEventWindowUpdate, window);
1166                                                 ::ValidateRect(hwnd, NULL);
1167                                         }
1168                                         else {
1169                                                 eventHandled = true;
1170                                         }
1171                                         break;
1172                                 case WM_GETMINMAXINFO:
1173                                         /* The WM_GETMINMAXINFO message is sent to a window when the size or 
1174                                          * position of the window is about to change. An application can use 
1175                                          * this message to override the window's default maximized size and 
1176                                          * position, or its default minimum or maximum tracking size. 
1177                                          */
1178                                         processMinMaxInfo((MINMAXINFO *) lParam);
1179                                         /* Let DefWindowProc handle it. */
1180                                         break;
1181                                 case WM_SIZING:
1182                                 case WM_SIZE:
1183                                         /* The WM_SIZE message is sent to a window after its size has changed.
1184                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1185                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1186                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1187                                          * message without calling DefWindowProc.
1188                                          */
1189                                         /* we get first WM_SIZE before we fully init. So, do not dispatch before we continiously resizng */
1190                                         if (window->m_inLiveResize) {
1191                                                 system->pushEvent(processWindowEvent(GHOST_kEventWindowSize, window));
1192                                                 system->dispatchEvents();
1193                                         }
1194                                         else {
1195                                                 event = processWindowEvent(GHOST_kEventWindowSize, window);
1196                                         }
1197                                         break;
1198                                 case WM_CAPTURECHANGED:
1199                                         window->lostMouseCapture();
1200                                         break;
1201                                 case WM_MOVING:
1202                                         /* The WM_MOVING message is sent to a window that the user is moving. By processing
1203                                          * this message, an application can monitor the size and position of the drag rectangle
1204                                          * and, if needed, change its size or position.
1205                                          */
1206                                 case WM_MOVE:
1207                                         /* The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1208                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1209                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1210                                          * message without calling DefWindowProc. 
1211                                          */
1212                                         /* see WM_SIZE comment*/
1213                                         if (window->m_inLiveResize) {
1214                                                 system->pushEvent(processWindowEvent(GHOST_kEventWindowMove, window));
1215                                                 system->dispatchEvents();
1216                                         }
1217                                         else {
1218                                                 event = processWindowEvent(GHOST_kEventWindowMove, window);
1219                                         }
1220
1221                                         break;
1222                                 ////////////////////////////////////////////////////////////////////////
1223                                 // Window events, ignored
1224                                 ////////////////////////////////////////////////////////////////////////
1225                                 case WM_WINDOWPOSCHANGED:
1226                                 /* The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place
1227                                  * in the Z order has changed as a result of a call to the SetWindowPos function or
1228                                  * another window-management function.
1229                                  * The WM_SIZE and WM_MOVE messages are not sent if an application handles the
1230                                  * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1231                                  * to perform any move or size change processing during the WM_WINDOWPOSCHANGED
1232                                  * message without calling DefWindowProc.
1233                                  */
1234                                 case WM_ERASEBKGND:
1235                                 /* An application sends the WM_ERASEBKGND message when the window background must be
1236                                  * erased (for example, when a window is resized). The message is sent to prepare an
1237                                  * invalidated portion of a window for painting.
1238                                  */
1239                                 case WM_NCPAINT:
1240                                 /* An application sends the WM_NCPAINT message to a window when its frame must be painted. */
1241                                 case WM_NCACTIVATE:
1242                                 /* The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed
1243                                  * to indicate an active or inactive state.
1244                                  */
1245                                 case WM_DESTROY:
1246                                 /* The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window
1247                                  * procedure of the window being destroyed after the window is removed from the screen.
1248                                  * This message is sent first to the window being destroyed and then to the child windows
1249                                  * (if any) as they are destroyed. During the processing of the message, it can be assumed
1250                                  * that all child windows still exist.
1251                                  */
1252                                 case WM_NCDESTROY:
1253                                         /* The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The 
1254                                          * DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY
1255                                          * message. WM_DESTROY is used to free the allocated memory object associated with the window. 
1256                                          */
1257                                         break;
1258                                 case WM_KILLFOCUS:
1259                                         /* The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus. 
1260                                          * We want to prevent this if a window is still active and it loses focus to nowhere*/
1261                                         if (!wParam && hwnd == ::GetActiveWindow())
1262                                                 ::SetFocus(hwnd);
1263                                 case WM_SHOWWINDOW:
1264                                 /* The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown. */
1265                                 case WM_WINDOWPOSCHANGING:
1266                                 /* The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in
1267                                  * the Z order is about to change as a result of a call to the SetWindowPos function or
1268                                  * another window-management function.
1269                                  */
1270                                 case WM_SETFOCUS:
1271                                 /* The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus. */
1272                                         break;
1273                                 ////////////////////////////////////////////////////////////////////////
1274                                 // Other events
1275                                 ////////////////////////////////////////////////////////////////////////
1276                                 case WM_GETTEXT:
1277                                 /* An application sends a WM_GETTEXT message to copy the text that
1278                                  * corresponds to a window into a buffer provided by the caller.
1279                                  */
1280                                 case WM_ACTIVATEAPP:
1281                                 /* The WM_ACTIVATEAPP message is sent when a window belonging to a
1282                                  * different application than the active window is about to be activated.
1283                                  * The message is sent to the application whose window is being activated
1284                                  * and to the application whose window is being deactivated.
1285                                  */
1286                                 case WM_TIMER:
1287                                         /* The WIN32 docs say:
1288                                          * The WM_TIMER message is posted to the installing thread's message queue
1289                                          * when a timer expires. You can process the message by providing a WM_TIMER
1290                                          * case in the window procedure. Otherwise, the default window procedure will
1291                                          * call the TimerProc callback function specified in the call to the SetTimer
1292                                          * function used to install the timer. 
1293                                          *
1294                                          * In GHOST, we let DefWindowProc call the timer callback.
1295                                          */
1296                                         break;
1297
1298                         }
1299                 }
1300                 else {
1301                         // Event found for a window before the pointer to the class has been set.
1302                         GHOST_PRINT("GHOST_SystemWin32::wndProc: GHOST window event before creation\n");
1303                         /* These are events we typically miss at this point:
1304                          * WM_GETMINMAXINFO     0x24
1305                          * WM_NCCREATE                  0x81
1306                          * WM_NCCALCSIZE                0x83
1307                          * WM_CREATE                    0x01
1308                          * We let DefWindowProc do the work.
1309                          */
1310                 }
1311         }
1312         else {
1313                 // Events without valid hwnd
1314                 GHOST_PRINT("GHOST_SystemWin32::wndProc: event without window\n");
1315         }
1316
1317         if (event) {
1318                 system->pushEvent(event);
1319                 eventHandled = true;
1320         }
1321
1322         if (!eventHandled)
1323                 lResult = ::DefWindowProcW(hwnd, msg, wParam, lParam);
1324
1325         return lResult;
1326 }
1327
1328 GHOST_TUns8 *GHOST_SystemWin32::getClipboard(bool selection) const
1329 {
1330         char *temp_buff;
1331         
1332         if (IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL) ) {
1333                 wchar_t *buffer;
1334                 HANDLE hData = GetClipboardData(CF_UNICODETEXT);
1335                 if (hData == NULL) {
1336                         CloseClipboard();
1337                         return NULL;
1338                 }
1339                 buffer = (wchar_t *)GlobalLock(hData);
1340                 if (!buffer) {
1341                         CloseClipboard();
1342                         return NULL;
1343                 }
1344                 
1345                 temp_buff = alloc_utf_8_from_16(buffer, 0);
1346                 
1347                 /* Buffer mustn't be accessed after CloseClipboard
1348                  * it would like accessing free-d memory */
1349                 GlobalUnlock(hData);
1350                 CloseClipboard();
1351                 
1352                 return (GHOST_TUns8 *)temp_buff;
1353         }
1354         else if (IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL) ) {
1355                 char *buffer;
1356                 size_t len = 0;
1357                 HANDLE hData = GetClipboardData(CF_TEXT);
1358                 if (hData == NULL) {
1359                         CloseClipboard();
1360                         return NULL;
1361                 }
1362                 buffer = (char *)GlobalLock(hData);
1363                 if (!buffer) {
1364                         CloseClipboard();
1365                         return NULL;
1366                 }
1367                 
1368                 len = strlen(buffer);
1369                 temp_buff = (char *) malloc(len + 1);
1370                 strncpy(temp_buff, buffer, len);
1371                 temp_buff[len] = '\0';
1372                 
1373                 /* Buffer mustn't be accessed after CloseClipboard
1374                  * it would like accessing free-d memory */
1375                 GlobalUnlock(hData);
1376                 CloseClipboard();
1377                 
1378                 return (GHOST_TUns8 *)temp_buff;
1379         }
1380         else {
1381                 return NULL;
1382         }
1383 }
1384
1385 void GHOST_SystemWin32::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1386 {
1387         if (selection) {return; } // for copying the selection, used on X11
1388
1389         if (OpenClipboard(NULL)) {
1390                 HLOCAL clipbuffer;
1391                 wchar_t *data;
1392                 
1393                 if (buffer) {
1394                         size_t len = count_utf_16_from_8(buffer);
1395                         EmptyClipboard();
1396                         
1397                         clipbuffer = LocalAlloc(LMEM_FIXED, sizeof(wchar_t) * len);
1398                         data = (wchar_t *)GlobalLock(clipbuffer);
1399
1400                         conv_utf_8_to_16(buffer, data, len);
1401
1402                         LocalUnlock(clipbuffer);
1403                         SetClipboardData(CF_UNICODETEXT, clipbuffer);
1404                 }
1405                 CloseClipboard();
1406         }
1407         else {
1408                 return;
1409         }
1410 }
1411
1412 static DWORD GetParentProcessID(void)
1413 {
1414         HANDLE snapshot;
1415         PROCESSENTRY32 pe32 = {0};
1416         DWORD ppid = 0, pid = GetCurrentProcessId();
1417         snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
1418         if (snapshot == INVALID_HANDLE_VALUE) {
1419                 return -1;
1420         }
1421         pe32.dwSize = sizeof( pe32 );
1422         if (!Process32First(snapshot, &pe32)) {
1423                 CloseHandle(snapshot);
1424                 return -1;
1425         }
1426         do {
1427                 if (pe32.th32ProcessID == pid) {
1428                         ppid = pe32.th32ParentProcessID;
1429                         break;
1430                 }
1431         } while (Process32Next(snapshot, &pe32));
1432         CloseHandle(snapshot);
1433         return ppid;
1434 }
1435
1436 static bool getProcessName(int pid, char *buffer, int max_len)
1437 {
1438         bool result = false;
1439         HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
1440                                     FALSE, pid);
1441         if (handle) {
1442                 GetModuleFileNameEx(handle, 0, buffer, max_len);
1443                 result = true;
1444         }
1445         CloseHandle(handle);
1446         return result;
1447 }
1448
1449 static bool isStartedFromCommandPrompt()
1450 {
1451         HWND hwnd = GetConsoleWindow();
1452         
1453         if (hwnd) {
1454                 DWORD pid = (DWORD)-1;
1455                 DWORD ppid = GetParentProcessID();
1456                 char parent_name[MAX_PATH];
1457                 bool start_from_launcher = false;
1458
1459                 GetWindowThreadProcessId(hwnd, &pid);
1460                 if (getProcessName(ppid, parent_name, sizeof(parent_name))) {
1461                         char *filename = strrchr(parent_name, '\\');
1462                         if (filename != NULL) {
1463                                 start_from_launcher = strstr(filename, "blender.exe") != NULL;
1464                         }
1465                 }
1466
1467                 /* When we're starting from a wrapper we need to compare with parent process ID. */
1468                 if (pid == (start_from_launcher ? ppid : GetCurrentProcessId()))
1469                         return true;
1470         }
1471
1472         return false;
1473 }
1474
1475 int GHOST_SystemWin32::toggleConsole(int action)
1476 {
1477         switch (action)
1478         {
1479                 case 3: // startup: hide if not started from command prompt
1480                 {
1481                         if (isStartedFromCommandPrompt()) {
1482                                 ShowWindow(GetConsoleWindow(), SW_HIDE);
1483                                 m_consoleStatus = 0;
1484                         }
1485                         break;
1486                 }
1487                 case 0: // hide
1488                         ShowWindow(GetConsoleWindow(), SW_HIDE);
1489                         m_consoleStatus = 0;
1490                         break;
1491                 case 1: // show
1492                         ShowWindow(GetConsoleWindow(), SW_SHOW);
1493                         m_consoleStatus = 1;
1494                         break;
1495                 case 2: // toggle
1496                         ShowWindow(GetConsoleWindow(), m_consoleStatus ? SW_HIDE : SW_SHOW);
1497                         m_consoleStatus = !m_consoleStatus;
1498                         break;
1499         }
1500
1501
1502         return m_consoleStatus;
1503 }
1504
1505 int GHOST_SystemWin32::confirmQuit(GHOST_IWindow *window) const
1506 {
1507         return (MessageBox(window ? ((GHOST_WindowWin32 *)window)->getHWND() : 0, "Some changes have not been saved.\nDo you really want to quit?",
1508                            "Exit Blender", MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST) == IDOK);
1509 }