Merge branch 'master' into blender2.8
[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  * \author      Maarten Gribnau
32  */
33
34
35 #include "GHOST_SystemWin32.h"
36 #include "GHOST_EventDragnDrop.h"
37
38 #ifndef _WIN32_IE
39 #  define _WIN32_IE 0x0501 /* shipped before XP, so doesn't impose additional requirements */
40 #endif
41
42 #include <shlobj.h>
43 #include <tlhelp32.h>
44 #include <psapi.h>
45 #include <windowsx.h>
46
47 #include "utfconv.h"
48
49 #include "GHOST_DisplayManagerWin32.h"
50 #include "GHOST_EventButton.h"
51 #include "GHOST_EventCursor.h"
52 #include "GHOST_EventKey.h"
53 #include "GHOST_EventWheel.h"
54 #include "GHOST_TimerTask.h"
55 #include "GHOST_TimerManager.h"
56 #include "GHOST_WindowManager.h"
57 #include "GHOST_WindowWin32.h"
58
59 #if defined(WITH_GL_EGL)
60 #  include "GHOST_ContextEGL.h"
61 #else
62 #  include "GHOST_ContextWGL.h"
63 #endif
64
65 #ifdef WITH_INPUT_NDOF
66   #include "GHOST_NDOFManagerWin32.h"
67 #endif
68
69 // Key code values not found in winuser.h
70 #ifndef VK_MINUS
71 #define VK_MINUS 0xBD
72 #endif // VK_MINUS
73 #ifndef VK_SEMICOLON
74 #define VK_SEMICOLON 0xBA
75 #endif // VK_SEMICOLON
76 #ifndef VK_PERIOD
77 #define VK_PERIOD 0xBE
78 #endif // VK_PERIOD
79 #ifndef VK_COMMA
80 #define VK_COMMA 0xBC
81 #endif // VK_COMMA
82 #ifndef VK_QUOTE
83 #define VK_QUOTE 0xDE
84 #endif // VK_QUOTE
85 #ifndef VK_BACK_QUOTE
86 #define VK_BACK_QUOTE 0xC0
87 #endif // VK_BACK_QUOTE
88 #ifndef VK_SLASH
89 #define VK_SLASH 0xBF
90 #endif // VK_SLASH
91 #ifndef VK_BACK_SLASH
92 #define VK_BACK_SLASH 0xDC
93 #endif // VK_BACK_SLASH
94 #ifndef VK_EQUALS
95 #define VK_EQUALS 0xBB
96 #endif // VK_EQUALS
97 #ifndef VK_OPEN_BRACKET
98 #define VK_OPEN_BRACKET 0xDB
99 #endif // VK_OPEN_BRACKET
100 #ifndef VK_CLOSE_BRACKET
101 #define VK_CLOSE_BRACKET 0xDD
102 #endif // VK_CLOSE_BRACKET
103 #ifndef VK_GR_LESS
104 #define VK_GR_LESS 0xE2
105 #endif // VK_GR_LESS
106
107 #ifndef VK_MEDIA_NEXT_TRACK
108 #define VK_MEDIA_NEXT_TRACK 0xB0
109 #endif // VK_MEDIA_NEXT_TRACK
110 #ifndef VK_MEDIA_PREV_TRACK
111 #define VK_MEDIA_PREV_TRACK 0xB1
112 #endif // VK_MEDIA_PREV_TRACK
113 #ifndef VK_MEDIA_STOP
114 #define VK_MEDIA_STOP 0xB2
115 #endif // VK_MEDIA_STOP
116 #ifndef VK_MEDIA_PLAY_PAUSE
117 #define VK_MEDIA_PLAY_PAUSE 0xB3
118 #endif // VK_MEDIA_PLAY_PAUSE
119
120 // Window message newer than Windows 7
121 #ifndef WM_DPICHANGED
122 #define WM_DPICHANGED 0x02E0
123 #endif // WM_DPICHANGED
124
125 /* Workaround for some laptop touchpads, some of which seems to
126  * have driver issues which makes it so window function receives
127  * the message, but PeekMessage doesn't pick those messages for
128  * some reason.
129  *
130  * We send a dummy WM_USER message to force PeekMessage to receive
131  * something, making it so blender's window manager sees the new
132  * messages coming in.
133  */
134 #define BROKEN_PEEK_TOUCHPAD
135
136 static void initRawInput()
137 {
138 #ifdef WITH_INPUT_NDOF
139   #define DEVICE_COUNT 2
140 #else
141   #define DEVICE_COUNT 1
142 #endif
143
144         RAWINPUTDEVICE devices[DEVICE_COUNT];
145         memset(devices, 0, DEVICE_COUNT * sizeof(RAWINPUTDEVICE));
146
147         // Initiates WM_INPUT messages from keyboard
148         // That way GHOST can retrieve true keys
149         devices[0].usUsagePage = 0x01;
150         devices[0].usUsage = 0x06; /* http://msdn.microsoft.com/en-us/windows/hardware/gg487473.aspx */
151
152 #ifdef WITH_INPUT_NDOF
153         // multi-axis mouse (SpaceNavigator, etc.)
154         devices[1].usUsagePage = 0x01;
155         devices[1].usUsage = 0x08;
156 #endif
157
158         if (RegisterRawInputDevices(devices, DEVICE_COUNT, sizeof(RAWINPUTDEVICE)))
159                 ;  // yay!
160         else
161                 GHOST_PRINTF("could not register for RawInput: %d\n", (int)GetLastError());
162
163 #undef DEVICE_COUNT
164 }
165
166 #ifndef DPI_ENUMS_DECLARED
167 typedef enum PROCESS_DPI_AWARENESS {
168         PROCESS_DPI_UNAWARE = 0,
169         PROCESS_SYSTEM_DPI_AWARE = 1,
170         PROCESS_PER_MONITOR_DPI_AWARE = 2
171 } PROCESS_DPI_AWARENESS;
172
173 typedef enum MONITOR_DPI_TYPE {
174         MDT_EFFECTIVE_DPI = 0,
175         MDT_ANGULAR_DPI = 1,
176         MDT_RAW_DPI = 2,
177         MDT_DEFAULT = MDT_EFFECTIVE_DPI
178 } MONITOR_DPI_TYPE;
179
180 #define USER_DEFAULT_SCREEN_DPI 96
181
182 #define DPI_ENUMS_DECLARED
183 #endif
184 typedef HRESULT(API * GHOST_WIN32_SetProcessDpiAwareness)(PROCESS_DPI_AWARENESS);
185 typedef BOOL(API * GHOST_WIN32_EnableNonClientDpiScaling)(HWND);
186
187 GHOST_SystemWin32::GHOST_SystemWin32()
188         : m_hasPerformanceCounter(false), m_freq(0), m_start(0)
189 {
190         m_displayManager = new GHOST_DisplayManagerWin32();
191         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::GHOST_SystemWin32(): m_displayManager==0\n");
192         m_displayManager->initialize();
193
194         m_consoleStatus = 1;
195
196         // Tell Windows we are per monitor DPI aware. This disables the default
197         // blurry scaling and enables WM_DPICHANGED to allow us to draw at proper DPI.
198         HMODULE m_shcore = ::LoadLibrary("Shcore.dll");
199         if (m_shcore) {
200                 GHOST_WIN32_SetProcessDpiAwareness fpSetProcessDpiAwareness =
201                         (GHOST_WIN32_SetProcessDpiAwareness) ::GetProcAddress(m_shcore, "SetProcessDpiAwareness");
202
203                 if (fpSetProcessDpiAwareness) {
204                         fpSetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE);
205                 }
206         }
207
208         // Check if current keyboard layout uses AltGr and save keylayout ID for
209         // specialized handling if keys like VK_OEM_*. I.e. french keylayout
210         // generates VK_OEM_8 for their exclamation key (key left of right shift)
211         this->handleKeyboardChange();
212         // Require COM for GHOST_DropTargetWin32 created in GHOST_WindowWin32.
213         OleInitialize(0);
214
215 #ifdef WITH_INPUT_NDOF
216         m_ndofManager = new GHOST_NDOFManagerWin32(*this);
217 #endif
218 }
219
220 GHOST_SystemWin32::~GHOST_SystemWin32()
221 {
222         // Shutdown COM
223         OleUninitialize();
224         toggleConsole(1);
225 }
226
227
228 GHOST_TUns64 GHOST_SystemWin32::getMilliSeconds() const
229 {
230         // Hardware does not support high resolution timers. We will use GetTickCount instead then.
231         if (!m_hasPerformanceCounter) {
232                 return ::GetTickCount();
233         }
234
235         // Retrieve current count
236         __int64 count = 0;
237         ::QueryPerformanceCounter((LARGE_INTEGER *)&count);
238
239         // Calculate the time passed since system initialization.
240         __int64 delta = 1000 * (count - m_start);
241
242         GHOST_TUns64 t = (GHOST_TUns64)(delta / m_freq);
243         return t;
244 }
245
246
247 GHOST_TUns8 GHOST_SystemWin32::getNumDisplays() const
248 {
249         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::getNumDisplays(): m_displayManager==0\n");
250         GHOST_TUns8 numDisplays;
251         m_displayManager->getNumDisplays(numDisplays);
252         return numDisplays;
253 }
254
255
256 void GHOST_SystemWin32::getMainDisplayDimensions(GHOST_TUns32 &width, GHOST_TUns32 &height) const
257 {
258         width = ::GetSystemMetrics(SM_CXSCREEN);
259         height = ::GetSystemMetrics(SM_CYSCREEN);
260 }
261
262 void GHOST_SystemWin32::getAllDisplayDimensions(GHOST_TUns32 &width, GHOST_TUns32 &height) const
263 {
264         width = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
265         height = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
266 }
267
268 GHOST_IWindow *GHOST_SystemWin32::createWindow(
269         const STR_String &title,
270         GHOST_TInt32 left, GHOST_TInt32 top,
271         GHOST_TUns32 width, GHOST_TUns32 height,
272         GHOST_TWindowState state, GHOST_TDrawingContextType type,
273         GHOST_GLSettings glSettings,
274         const bool exclusive,
275         const GHOST_TEmbedderWindowID parentWindow)
276 {
277         GHOST_WindowWin32 *window =
278                 new GHOST_WindowWin32(
279                         this,
280                         title,
281                         left,
282                         top,
283                         width,
284                         height,
285                         state,
286                         type,
287                         ((glSettings.flags & GHOST_glStereoVisual) != 0),
288                         ((glSettings.flags & GHOST_glAlphaBackground) != 0),
289                         glSettings.numOfAASamples,
290                         parentWindow,
291                         ((glSettings.flags & GHOST_glDebugContext) != 0));
292
293         if (window->getValid()) {
294                 // Store the pointer to the window
295                 m_windowManager->addWindow(window);
296                 m_windowManager->setActiveWindow(window);
297         }
298         else {
299                 GHOST_PRINT("GHOST_SystemWin32::createWindow(): window invalid\n");
300                 delete window;
301                 window = NULL;
302         }
303
304         return window;
305 }
306
307
308 /**
309  * Create a new offscreen context.
310  * Never explicitly delete the window, use disposeContext() instead.
311  * \return  The new context (or 0 if creation failed).
312  */
313 GHOST_IContext *GHOST_SystemWin32::createOffscreenContext()
314 {
315         bool debug_context = false; /* TODO: inform as a parameter */
316
317         GHOST_Context *context;
318
319         HWND wnd = CreateWindowA("STATIC",
320                 "BlenderGLEW",
321                 WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
322                 0, 0, 64, 64,
323                 NULL, NULL,
324                 GetModuleHandle(NULL), NULL
325         );
326
327         HDC  mHDC = GetDC(wnd);
328         HDC  prev_hdc = wglGetCurrentDC();
329         HGLRC prev_context = wglGetCurrentContext();
330 #if defined(WITH_GL_PROFILE_CORE)
331         for (int minor = 5; minor >= 0; --minor) {
332                         context = new GHOST_ContextWGL(
333                             false, true, 0,
334                             wnd, mHDC,
335                             WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
336                             4, minor,
337                             (debug_context ? WGL_CONTEXT_DEBUG_BIT_ARB : 0),
338                             GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY);
339
340                         if (context->initializeDrawingContext()) {
341                                 goto finished;
342                         }
343                         else {
344                                 delete context;
345                         }
346                 }
347
348                 context = new GHOST_ContextWGL(
349                     false, true, 0,
350                     wnd, mHDC,
351                     WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
352                     3, 3,
353                     (debug_context ? WGL_CONTEXT_DEBUG_BIT_ARB : 0),
354                     GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY);
355
356                 if (context->initializeDrawingContext()) {
357                         goto finished;
358                 }
359                 else {
360                         MessageBox(
361                                 NULL,
362                                 "Blender requires a graphics driver with at least OpenGL 3.3 support.\n\n"
363                                 "The program will now close.",
364                                 "Blender - Unsupported Graphics Driver!",
365                                 MB_OK | MB_ICONERROR);
366                         delete context;
367                         exit();
368                 }
369
370 #elif defined(WITH_GL_PROFILE_COMPAT)
371                 // ask for 2.1 context, driver gives any GL version >= 2.1 (hopefully the latest compatibility profile)
372                 // 2.1 ignores the profile bit & is incompatible with core profile
373                 context = new GHOST_ContextWGL(
374                         false, true, 0,
375                         NULL, NULL,
376                         0, // no profile bit
377                         2, 1,
378                         (debug_context ? WGL_CONTEXT_DEBUG_BIT_ARB : 0),
379                         GHOST_OPENGL_WGL_RESET_NOTIFICATION_STRATEGY);
380
381                 if (context->initializeDrawingContext()) {
382                         return context;
383                 }
384                 else {
385                         delete context;
386                 }
387 #else
388 #  error // must specify either core or compat at build time
389 #endif
390 finished:
391         wglMakeCurrent(prev_hdc, prev_context);
392         return context;
393 }
394
395 /**
396  * Dispose of a context.
397  * \param   context Pointer to the context to be disposed.
398  * \return  Indication of success.
399  */
400 GHOST_TSuccess GHOST_SystemWin32::disposeContext(GHOST_IContext *context)
401 {
402         delete context;
403
404         return GHOST_kSuccess;
405 }
406
407
408 bool GHOST_SystemWin32::processEvents(bool waitForEvent)
409 {
410         MSG msg;
411         bool hasEventHandled = false;
412
413         do {
414                 GHOST_TimerManager *timerMgr = getTimerManager();
415
416                 if (waitForEvent && !::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
417 #if 1
418                         ::Sleep(1);
419 #else
420                         GHOST_TUns64 next = timerMgr->nextFireTime();
421                         GHOST_TInt64 maxSleep = next - getMilliSeconds();
422
423                         if (next == GHOST_kFireTimeNever) {
424                                 ::WaitMessage();
425                         }
426                         else if (maxSleep >= 0.0) {
427                                 ::SetTimer(NULL, 0, maxSleep, NULL);
428                                 ::WaitMessage();
429                                 ::KillTimer(NULL, 0);
430                         }
431 #endif
432                 }
433
434                 if (timerMgr->fireTimers(getMilliSeconds())) {
435                         hasEventHandled = true;
436                 }
437
438                 // Process all the events waiting for us
439                 while (::PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE) != 0) {
440                         // TranslateMessage doesn't alter the message, and doesn't change our raw keyboard data.
441                         // Needed for MapVirtualKey or if we ever need to get chars from wm_ime_char or similar.
442                         ::TranslateMessage(&msg);
443                         ::DispatchMessageW(&msg);
444                 }
445
446                 if (hasEventHandled == false) {
447                         // Check if we have events handled by the system
448                         // (for example the `GHOST_kEventWindowClose`).
449                         hasEventHandled = m_eventManager->getNumEvents() != 0;
450                 }
451
452         } while (waitForEvent && !hasEventHandled);
453
454         return hasEventHandled;
455 }
456
457
458 GHOST_TSuccess GHOST_SystemWin32::getCursorPosition(GHOST_TInt32 &x, GHOST_TInt32 &y) const
459 {
460         POINT point;
461         if (::GetCursorPos(&point)) {
462                 x = point.x;
463                 y = point.y;
464                 return GHOST_kSuccess;
465         }
466         return GHOST_kFailure;
467 }
468
469
470 GHOST_TSuccess GHOST_SystemWin32::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y)
471 {
472         if (!::GetActiveWindow())
473                 return GHOST_kFailure;
474         return ::SetCursorPos(x, y) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
475 }
476
477
478 GHOST_TSuccess GHOST_SystemWin32::getModifierKeys(GHOST_ModifierKeys &keys) const
479 {
480         bool down = HIBYTE(::GetKeyState(VK_LSHIFT)) != 0;
481         keys.set(GHOST_kModifierKeyLeftShift, down);
482         down = HIBYTE(::GetKeyState(VK_RSHIFT)) != 0;
483         keys.set(GHOST_kModifierKeyRightShift, down);
484
485         down = HIBYTE(::GetKeyState(VK_LMENU)) != 0;
486         keys.set(GHOST_kModifierKeyLeftAlt, down);
487         down = HIBYTE(::GetKeyState(VK_RMENU)) != 0;
488         keys.set(GHOST_kModifierKeyRightAlt, down);
489
490         down = HIBYTE(::GetKeyState(VK_LCONTROL)) != 0;
491         keys.set(GHOST_kModifierKeyLeftControl, down);
492         down = HIBYTE(::GetKeyState(VK_RCONTROL)) != 0;
493         keys.set(GHOST_kModifierKeyRightControl, down);
494
495         bool lwindown = HIBYTE(::GetKeyState(VK_LWIN)) != 0;
496         bool rwindown = HIBYTE(::GetKeyState(VK_RWIN)) != 0;
497         if (lwindown || rwindown)
498                 keys.set(GHOST_kModifierKeyOS, true);
499         else
500                 keys.set(GHOST_kModifierKeyOS, false);
501         return GHOST_kSuccess;
502 }
503
504
505 GHOST_TSuccess GHOST_SystemWin32::getButtons(GHOST_Buttons &buttons) const
506 {
507         /* Check for swapped buttons (left-handed mouse buttons)
508          * GetAsyncKeyState() will give back the state of the physical mouse buttons.
509          */
510         bool swapped = ::GetSystemMetrics(SM_SWAPBUTTON) == TRUE;
511
512         bool down = HIBYTE(::GetKeyState(VK_LBUTTON)) != 0;
513         buttons.set(swapped ? GHOST_kButtonMaskRight : GHOST_kButtonMaskLeft, down);
514
515         down = HIBYTE(::GetKeyState(VK_MBUTTON)) != 0;
516         buttons.set(GHOST_kButtonMaskMiddle, down);
517
518         down = HIBYTE(::GetKeyState(VK_RBUTTON)) != 0;
519         buttons.set(swapped ? GHOST_kButtonMaskLeft : GHOST_kButtonMaskRight, down);
520         return GHOST_kSuccess;
521 }
522
523
524 GHOST_TSuccess GHOST_SystemWin32::init()
525 {
526         GHOST_TSuccess success = GHOST_System::init();
527
528         /* Disable scaling on high DPI displays on Vista */
529         HMODULE
530             user32 = ::LoadLibraryA("user32.dll");
531         typedef BOOL (WINAPI * LPFNSETPROCESSDPIAWARE)();
532         LPFNSETPROCESSDPIAWARE SetProcessDPIAware =
533             (LPFNSETPROCESSDPIAWARE)GetProcAddress(user32, "SetProcessDPIAware");
534         if (SetProcessDPIAware)
535                 SetProcessDPIAware();
536         FreeLibrary(user32);
537         initRawInput();
538
539         // Determine whether this system has a high frequency performance counter. */
540         m_hasPerformanceCounter = ::QueryPerformanceFrequency((LARGE_INTEGER *)&m_freq) == TRUE;
541         if (m_hasPerformanceCounter) {
542                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer available\n");
543                 ::QueryPerformanceCounter((LARGE_INTEGER *)&m_start);
544         }
545         else {
546                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer not available\n");
547         }
548
549         if (success) {
550                 WNDCLASSW wc = {0};
551                 wc.style = CS_HREDRAW | CS_VREDRAW;
552                 wc.lpfnWndProc = s_wndProc;
553                 wc.cbClsExtra = 0;
554                 wc.cbWndExtra = 0;
555                 wc.hInstance = ::GetModuleHandle(0);
556                 wc.hIcon = ::LoadIcon(wc.hInstance, "APPICON");
557
558                 if (!wc.hIcon) {
559                         ::LoadIcon(NULL, IDI_APPLICATION);
560                 }
561                 wc.hCursor = ::LoadCursor(0, IDC_ARROW);
562                 wc.hbrBackground =
563 #ifdef INW32_COMPISITING
564                         (HBRUSH)CreateSolidBrush
565 #endif
566                         (0x00000000);
567                 wc.lpszMenuName = 0;
568                 wc.lpszClassName = L"GHOST_WindowClass";
569
570                 // Use RegisterClassEx for setting small icon
571                 if (::RegisterClassW(&wc) == 0) {
572                         success = GHOST_kFailure;
573                 }
574         }
575
576         return success;
577 }
578
579
580 GHOST_TSuccess GHOST_SystemWin32::exit()
581 {
582         return GHOST_System::exit();
583 }
584
585 GHOST_TKey GHOST_SystemWin32::hardKey(RAWINPUT const &raw, int *keyDown, char *vk)
586 {
587         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
588         GHOST_TKey key = GHOST_kKeyUnknown;
589         GHOST_ModifierKeys modifiers;
590         system->retrieveModifierKeys(modifiers);
591
592         // RI_KEY_BREAK doesn't work for sticky keys release, so we also
593         // check for the up message
594         unsigned int msg = raw.data.keyboard.Message;
595         *keyDown = !(raw.data.keyboard.Flags & RI_KEY_BREAK) && msg != WM_KEYUP && msg != WM_SYSKEYUP;
596
597         key = this->convertKey(raw.data.keyboard.VKey, raw.data.keyboard.MakeCode, (raw.data.keyboard.Flags & (RI_KEY_E1 | RI_KEY_E0)));
598
599         // extra handling of modifier keys: don't send repeats out from GHOST
600         if (key >= GHOST_kKeyLeftShift && key <= GHOST_kKeyRightAlt) {
601                 bool changed = false;
602                 GHOST_TModifierKeyMask modifier;
603                 switch (key) {
604                         case GHOST_kKeyLeftShift:
605                         {
606                                 changed = (modifiers.get(GHOST_kModifierKeyLeftShift) != (bool)*keyDown);
607                                 modifier = GHOST_kModifierKeyLeftShift;
608                                 break;
609                         }
610                         case GHOST_kKeyRightShift:
611                         {
612                                 changed = (modifiers.get(GHOST_kModifierKeyRightShift) != (bool)*keyDown);
613                                 modifier = GHOST_kModifierKeyRightShift;
614                                 break;
615                         }
616                         case GHOST_kKeyLeftControl:
617                         {
618                                 changed = (modifiers.get(GHOST_kModifierKeyLeftControl) != (bool)*keyDown);
619                                 modifier = GHOST_kModifierKeyLeftControl;
620                                 break;
621                         }
622                         case GHOST_kKeyRightControl:
623                         {
624                                 changed = (modifiers.get(GHOST_kModifierKeyRightControl) != (bool)*keyDown);
625                                 modifier = GHOST_kModifierKeyRightControl;
626                                 break;
627                         }
628                         case GHOST_kKeyLeftAlt:
629                         {
630                                 changed = (modifiers.get(GHOST_kModifierKeyLeftAlt) != (bool)*keyDown);
631                                 modifier = GHOST_kModifierKeyLeftAlt;
632                                 break;
633                         }
634                         case GHOST_kKeyRightAlt:
635                         {
636                                 changed = (modifiers.get(GHOST_kModifierKeyRightAlt) != (bool)*keyDown);
637                                 modifier = GHOST_kModifierKeyRightAlt;
638                                 break;
639                         }
640                         default:
641                                 break;
642                 }
643
644                 if (changed) {
645                         modifiers.set(modifier, (bool)*keyDown);
646                         system->storeModifierKeys(modifiers);
647                 }
648                 else {
649                         key = GHOST_kKeyUnknown;
650                 }
651         }
652
653
654         if (vk) *vk = raw.data.keyboard.VKey;
655
656         return key;
657 }
658
659 //! note: this function can be extended to include other exotic cases as they arise.
660 // This function was added in response to bug [#25715]
661 // This is going to be a long list [T42426]
662 GHOST_TKey GHOST_SystemWin32::processSpecialKey(short vKey, short scanCode) const
663 {
664         GHOST_TKey key = GHOST_kKeyUnknown;
665         switch (PRIMARYLANGID(m_langId)) {
666                 case LANG_FRENCH:
667                         if (vKey == VK_OEM_8) key = GHOST_kKeyF13;  // oem key; used purely for shortcuts .
668                         break;
669                 case LANG_ENGLISH:
670                         if (SUBLANGID(m_langId) == SUBLANG_ENGLISH_UK && vKey == VK_OEM_8) // "`¬"
671                                 key = GHOST_kKeyAccentGrave;
672                         break;
673         }
674
675         return key;
676 }
677
678 GHOST_TKey GHOST_SystemWin32::convertKey(short vKey, short scanCode, short extend) const
679 {
680         GHOST_TKey key;
681
682         if ((vKey >= '0') && (vKey <= '9')) {
683                 // VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
684                 key = (GHOST_TKey)(vKey - '0' + GHOST_kKey0);
685         }
686         else if ((vKey >= 'A') && (vKey <= 'Z')) {
687                 // VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
688                 key = (GHOST_TKey)(vKey - 'A' + GHOST_kKeyA);
689         }
690         else if ((vKey >= VK_F1) && (vKey <= VK_F24)) {
691                 key = (GHOST_TKey)(vKey - VK_F1 + GHOST_kKeyF1);
692         }
693         else {
694                 switch (vKey) {
695                         case VK_RETURN:
696                                 key = (extend) ? GHOST_kKeyNumpadEnter : GHOST_kKeyEnter; break;
697
698                         case VK_BACK:     key = GHOST_kKeyBackSpace;        break;
699                         case VK_TAB:      key = GHOST_kKeyTab;              break;
700                         case VK_ESCAPE:   key = GHOST_kKeyEsc;              break;
701                         case VK_SPACE:    key = GHOST_kKeySpace;            break;
702
703                         case VK_INSERT:
704                         case VK_NUMPAD0:
705                                 key = (extend) ? GHOST_kKeyInsert : GHOST_kKeyNumpad0;  break;
706                         case VK_END:
707                         case VK_NUMPAD1:
708                                 key = (extend) ? GHOST_kKeyEnd : GHOST_kKeyNumpad1; break;
709                         case VK_DOWN:
710                         case VK_NUMPAD2:
711                                 key = (extend) ? GHOST_kKeyDownArrow : GHOST_kKeyNumpad2;   break;
712                         case VK_NEXT:
713                         case VK_NUMPAD3:
714                                 key = (extend) ?  GHOST_kKeyDownPage : GHOST_kKeyNumpad3;   break;
715                         case VK_LEFT:
716                         case VK_NUMPAD4:
717                                 key = (extend) ? GHOST_kKeyLeftArrow : GHOST_kKeyNumpad4;   break;
718                         case VK_CLEAR:
719                         case VK_NUMPAD5:
720                                 key = (extend) ? GHOST_kKeyUnknown : GHOST_kKeyNumpad5;  break;
721                         case VK_RIGHT:
722                         case VK_NUMPAD6:
723                                 key = (extend) ? GHOST_kKeyRightArrow : GHOST_kKeyNumpad6;  break;
724                         case VK_HOME:
725                         case VK_NUMPAD7:
726                                 key = (extend) ? GHOST_kKeyHome : GHOST_kKeyNumpad7;    break;
727                         case VK_UP:
728                         case VK_NUMPAD8:
729                                 key = (extend) ? GHOST_kKeyUpArrow : GHOST_kKeyNumpad8; break;
730                         case VK_PRIOR:
731                         case VK_NUMPAD9:
732                                 key = (extend) ? GHOST_kKeyUpPage : GHOST_kKeyNumpad9;  break;
733                         case VK_DECIMAL:
734                         case VK_DELETE:
735                                 key = (extend) ? GHOST_kKeyDelete : GHOST_kKeyNumpadPeriod; break;
736
737                         case VK_SNAPSHOT: key = GHOST_kKeyPrintScreen;      break;
738                         case VK_PAUSE:    key = GHOST_kKeyPause;            break;
739                         case VK_MULTIPLY: key = GHOST_kKeyNumpadAsterisk;   break;
740                         case VK_SUBTRACT: key = GHOST_kKeyNumpadMinus;      break;
741                         case VK_DIVIDE:   key = GHOST_kKeyNumpadSlash;      break;
742                         case VK_ADD:      key = GHOST_kKeyNumpadPlus;       break;
743
744                         case VK_SEMICOLON:      key = GHOST_kKeySemicolon;      break;
745                         case VK_EQUALS:         key = GHOST_kKeyEqual;          break;
746                         case VK_COMMA:          key = GHOST_kKeyComma;          break;
747                         case VK_MINUS:          key = GHOST_kKeyMinus;          break;
748                         case VK_PERIOD:         key = GHOST_kKeyPeriod;         break;
749                         case VK_SLASH:          key = GHOST_kKeySlash;          break;
750                         case VK_BACK_QUOTE:     key = GHOST_kKeyAccentGrave;    break;
751                         case VK_OPEN_BRACKET:   key = GHOST_kKeyLeftBracket;    break;
752                         case VK_BACK_SLASH:     key = GHOST_kKeyBackslash;      break;
753                         case VK_CLOSE_BRACKET:  key = GHOST_kKeyRightBracket;   break;
754                         case VK_QUOTE:          key = GHOST_kKeyQuote;          break;
755                         case VK_GR_LESS:        key = GHOST_kKeyGrLess;         break;
756
757                         case VK_SHIFT:
758                                 /* Check single shift presses */
759                                 if (scanCode == 0x36) {
760                                         key = GHOST_kKeyRightShift;
761                                 }
762                                 else if (scanCode == 0x2a) {
763                                         key = GHOST_kKeyLeftShift;
764                                 }
765                                 else {
766                                         /* Must be a combination SHIFT (Left or Right) + a Key
767                                          * Ignore this as the next message will contain
768                                          * the desired "Key" */
769                                         key = GHOST_kKeyUnknown;
770                                 }
771                                 break;
772                         case VK_CONTROL:
773                                 key = (extend) ? GHOST_kKeyRightControl : GHOST_kKeyLeftControl;
774                                 break;
775                         case VK_MENU:
776                                 key = (extend) ? GHOST_kKeyRightAlt : GHOST_kKeyLeftAlt;
777                                 break;
778                         case VK_LWIN:
779                         case VK_RWIN:
780                                 key = GHOST_kKeyOS;
781                                 break;
782                         case VK_NUMLOCK: key = GHOST_kKeyNumLock; break;
783                         case VK_SCROLL: key = GHOST_kKeyScrollLock; break;
784                         case VK_CAPITAL: key = GHOST_kKeyCapsLock; break;
785                         case VK_OEM_8:
786                                 key = ((GHOST_SystemWin32 *)getSystem())->processSpecialKey(vKey, scanCode);
787                                 break;
788                         case VK_MEDIA_PLAY_PAUSE: key = GHOST_kKeyMediaPlay; break;
789                         case VK_MEDIA_STOP: key = GHOST_kKeyMediaStop; break;
790                         case VK_MEDIA_PREV_TRACK: key = GHOST_kKeyMediaFirst; break;
791                         case VK_MEDIA_NEXT_TRACK: key = GHOST_kKeyMediaLast; break;
792                         default:
793                                 key = GHOST_kKeyUnknown;
794                                 break;
795                 }
796         }
797
798         return key;
799 }
800
801 GHOST_EventButton *GHOST_SystemWin32::processButtonEvent(
802         GHOST_TEventType type,
803         GHOST_WindowWin32 *window,
804         GHOST_TButtonMask mask)
805 {
806         return new GHOST_EventButton(getSystem()->getMilliSeconds(), type, window, mask);
807 }
808
809
810 GHOST_EventCursor *GHOST_SystemWin32::processCursorEvent(GHOST_TEventType type, GHOST_WindowWin32 *window)
811 {
812         GHOST_TInt32 x_screen, y_screen;
813         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *) getSystem();
814
815         system->getCursorPosition(x_screen, y_screen);
816
817         /* TODO: CHECK IF THIS IS A TABLET EVENT */
818         bool is_tablet = false;
819
820         if (is_tablet == false && window->getCursorGrabModeIsWarp()) {
821                 GHOST_TInt32 x_new = x_screen;
822                 GHOST_TInt32 y_new = y_screen;
823                 GHOST_TInt32 x_accum, y_accum;
824                 GHOST_Rect bounds;
825
826                 /* fallback to window bounds */
827                 if (window->getCursorGrabBounds(bounds) == GHOST_kFailure) {
828                         window->getClientBounds(bounds);
829                 }
830
831                 /* could also clamp to screen bounds
832                  * wrap with a window outside the view will fail atm  */
833
834                 bounds.wrapPoint(x_new, y_new, 2); /* offset of one incase blender is at screen bounds */
835
836                 window->getCursorGrabAccum(x_accum, y_accum);
837                 if (x_new != x_screen || y_new != y_screen) {
838                         /* when wrapping we don't need to add an event because the
839                          * setCursorPosition call will cause a new event after */
840                         system->setCursorPosition(x_new, y_new); /* wrap */
841                         window->setCursorGrabAccum(x_accum + (x_screen - x_new), y_accum + (y_screen - y_new));
842                 }
843                 else {
844                         return new GHOST_EventCursor(system->getMilliSeconds(),
845                                                      GHOST_kEventCursorMove,
846                                                      window,
847                                                      x_screen + x_accum,
848                                                      y_screen + y_accum
849                                                      );
850                 }
851
852         }
853         else {
854                 return new GHOST_EventCursor(system->getMilliSeconds(),
855                                              GHOST_kEventCursorMove,
856                                              window,
857                                              x_screen,
858                                              y_screen
859                                              );
860         }
861         return NULL;
862 }
863
864
865 void GHOST_SystemWin32::processWheelEvent(GHOST_WindowWin32 *window, WPARAM wParam, LPARAM lParam)
866 {
867         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
868
869         int acc = system->m_wheelDeltaAccum;
870         int delta = GET_WHEEL_DELTA_WPARAM(wParam);
871
872         if (acc * delta < 0) {
873                 // scroll direction reversed.
874                 acc = 0;
875         }
876         acc += delta;
877         int direction = (acc >= 0) ? 1 : -1;
878         acc = abs(acc);
879
880         while (acc >= WHEEL_DELTA) {
881                 system->pushEvent(new GHOST_EventWheel(system->getMilliSeconds(), window, direction));
882                 acc -= WHEEL_DELTA;
883         }
884         system->m_wheelDeltaAccum = acc * direction;
885 }
886
887
888 GHOST_EventKey *GHOST_SystemWin32::processKeyEvent(GHOST_WindowWin32 *window, RAWINPUT const &raw)
889 {
890         int keyDown = 0;
891         char vk;
892         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
893         GHOST_TKey key = system->hardKey(raw, &keyDown, &vk);
894         GHOST_EventKey *event;
895
896         if (key != GHOST_kKeyUnknown) {
897                 char utf8_char[6] = {0};
898                 char ascii = 0;
899
900                 wchar_t utf16[3] = {0};
901                 BYTE state[256] = {0};
902                 int r;
903                 GetKeyboardState((PBYTE)state);
904
905                 // don't call ToUnicodeEx on dead keys as it clears the buffer and so won't allow diacritical composition.
906                 if (MapVirtualKeyW(vk, 2) != 0) {
907                         // todo: ToUnicodeEx can respond with up to 4 utf16 chars (only 2 here). Could be up to 24 utf8 bytes.
908                         if ((r = ToUnicodeEx(vk, raw.data.keyboard.MakeCode, state, utf16, 2, 0, system->m_keylayout))) {
909                                 if ((r > 0 && r < 3)) {
910                                         utf16[r] = 0;
911                                         conv_utf_16_to_8(utf16, utf8_char, 6);
912                                 }
913                                 else if (r == -1) {
914                                         utf8_char[0] = '\0';
915                                 }
916                         }
917                 }
918
919                 if (!keyDown) {
920                         utf8_char[0] = '\0';
921                         ascii = '\0';
922                 }
923                 else {
924                         ascii = utf8_char[0] & 0x80 ? '?' : utf8_char[0];
925                 }
926
927                 event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown : GHOST_kEventKeyUp, window, key, ascii, utf8_char);
928
929                 // GHOST_PRINTF("%c\n", ascii); // we already get this info via EventPrinter
930         }
931         else {
932                 event = NULL;
933         }
934         return event;
935 }
936
937
938 GHOST_Event *GHOST_SystemWin32::processWindowEvent(GHOST_TEventType type, GHOST_WindowWin32 *window)
939 {
940         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
941
942         if (type == GHOST_kEventWindowActivate) {
943                 system->getWindowManager()->setActiveWindow(window);
944                 window->bringTabletContextToFront();
945         }
946
947         return new GHOST_Event(system->getMilliSeconds(), type, window);
948 }
949
950 #ifdef WITH_INPUT_IME
951 GHOST_Event *GHOST_SystemWin32::processImeEvent(GHOST_TEventType type, GHOST_WindowWin32 *window, GHOST_TEventImeData *data)
952 {
953         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
954         return new GHOST_EventIME(system->getMilliSeconds(), type, window, data);
955 }
956 #endif
957
958
959 GHOST_TSuccess GHOST_SystemWin32::pushDragDropEvent(
960         GHOST_TEventType eventType,
961         GHOST_TDragnDropTypes draggedObjectType,
962         GHOST_WindowWin32 *window,
963         int mouseX, int mouseY,
964         void *data)
965 {
966         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
967         return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
968                                                           eventType,
969                                                           draggedObjectType,
970                                                           window, mouseX, mouseY, data)
971                                  );
972 }
973
974 void GHOST_SystemWin32::processMinMaxInfo(MINMAXINFO *minmax)
975 {
976         minmax->ptMinTrackSize.x = 320;
977         minmax->ptMinTrackSize.y = 240;
978 }
979
980 #ifdef WITH_INPUT_NDOF
981 bool GHOST_SystemWin32::processNDOF(RAWINPUT const &raw)
982 {
983         bool eventSent = false;
984         GHOST_TUns64 now = getMilliSeconds();
985
986         static bool firstEvent = true;
987         if (firstEvent) { // determine exactly which device is plugged in
988                 RID_DEVICE_INFO info;
989                 unsigned infoSize = sizeof(RID_DEVICE_INFO);
990                 info.cbSize = infoSize;
991
992                 GetRawInputDeviceInfo(raw.header.hDevice, RIDI_DEVICEINFO, &info, &infoSize);
993                 if (info.dwType == RIM_TYPEHID)
994                         m_ndofManager->setDevice(info.hid.dwVendorId, info.hid.dwProductId);
995                 else
996                         GHOST_PRINT("<!> not a HID device... mouse/kb perhaps?\n");
997
998                 firstEvent = false;
999         }
1000
1001         // The NDOF manager sends button changes immediately, and *pretends* to
1002         // send motion. Mark as 'sent' so motion will always get dispatched.
1003         eventSent = true;
1004
1005         BYTE const *data = raw.data.hid.bRawData;
1006
1007         BYTE packetType = data[0];
1008         switch (packetType) {
1009                 case 1: // translation
1010                 {
1011                         const short *axis = (short *)(data + 1);
1012                         // massage into blender view coords (same goes for rotation)
1013                         const int t[3] = {axis[0], -axis[2], axis[1]};
1014                         m_ndofManager->updateTranslation(t, now);
1015
1016                         if (raw.data.hid.dwSizeHid == 13) {
1017                                 // this report also includes rotation
1018                                 const int r[3] = {-axis[3], axis[5], -axis[4]};
1019                                 m_ndofManager->updateRotation(r, now);
1020
1021                                 // I've never gotten one of these, has anyone else?
1022                                 GHOST_PRINT("ndof: combined T + R\n");
1023                         }
1024                         break;
1025                 }
1026                 case 2: // rotation
1027                 {
1028                         const short *axis = (short *)(data + 1);
1029                         const int r[3] = {-axis[0], axis[2], -axis[1]};
1030                         m_ndofManager->updateRotation(r, now);
1031                         break;
1032                 }
1033                 case 3: // buttons
1034                 {
1035                         int button_bits;
1036                         memcpy(&button_bits, data + 1, sizeof(button_bits));
1037                         m_ndofManager->updateButtons(button_bits, now);
1038                         break;
1039                 }
1040         }
1041         return eventSent;
1042 }
1043 #endif // WITH_INPUT_NDOF
1044
1045 LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1046 {
1047         GHOST_Event *event = NULL;
1048         bool eventHandled = false;
1049
1050         LRESULT lResult = 0;
1051         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
1052         GHOST_EventManager *eventManager = system->getEventManager();
1053         GHOST_ASSERT(system, "GHOST_SystemWin32::s_wndProc(): system not initialized");
1054
1055         if (hwnd) {
1056 #if 0
1057                 // Disabled due to bug in Intel drivers, see T51959
1058                 if(msg == WM_NCCREATE) {
1059                         // Tell Windows to automatically handle scaling of non-client areas
1060                         // such as the caption bar. EnableNonClientDpiScaling was introduced in Windows 10
1061                         HMODULE m_user32 = ::LoadLibrary("User32.dll");
1062                         if (m_user32) {
1063                                 GHOST_WIN32_EnableNonClientDpiScaling fpEnableNonClientDpiScaling =
1064                                         (GHOST_WIN32_EnableNonClientDpiScaling) ::GetProcAddress(m_user32, "EnableNonClientDpiScaling");
1065
1066                                 if (fpEnableNonClientDpiScaling) {
1067                                         fpEnableNonClientDpiScaling(hwnd);
1068                                 }
1069                         }
1070                 }
1071 #endif
1072
1073                 GHOST_WindowWin32 *window = (GHOST_WindowWin32 *)::GetWindowLongPtr(hwnd, GWLP_USERDATA);
1074                 if (window) {
1075                         switch (msg) {
1076                                 // we need to check if new key layout has AltGr
1077                                 case WM_INPUTLANGCHANGE:
1078                                 {
1079                                         system->handleKeyboardChange();
1080 #ifdef WITH_INPUT_IME
1081                                         window->getImeInput()->SetInputLanguage();
1082 #endif
1083                                         break;
1084                                 }
1085                                 ////////////////////////////////////////////////////////////////////////
1086                                 // Keyboard events, processed
1087                                 ////////////////////////////////////////////////////////////////////////
1088                                 case WM_INPUT:
1089                                 {
1090                                         // check WM_INPUT from input sink when ghost window is not in the foreground
1091                                         if (wParam == RIM_INPUTSINK) {
1092                                                 if (GetFocus() != hwnd) // WM_INPUT message not for this window
1093                                                         return 0;
1094                                         } //else wParam == RIM_INPUT
1095
1096                                         RAWINPUT raw;
1097                                         RAWINPUT *raw_ptr = &raw;
1098                                         UINT rawSize = sizeof(RAWINPUT);
1099
1100                                         GetRawInputData((HRAWINPUT)lParam, RID_INPUT, raw_ptr, &rawSize, sizeof(RAWINPUTHEADER));
1101
1102                                         switch (raw.header.dwType) {
1103                                                 case RIM_TYPEKEYBOARD:
1104                                                         event = processKeyEvent(window, raw);
1105                                                         if (!event) {
1106                                                                 GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ");
1107                                                                 GHOST_PRINT(msg);
1108                                                                 GHOST_PRINT(" key ignored\n");
1109                                                         }
1110                                                         break;
1111 #ifdef WITH_INPUT_NDOF
1112                                                 case RIM_TYPEHID:
1113                                                         if (system->processNDOF(raw)) {
1114                                                                 system->m_ndofManager->sendMotionEvent();
1115                                                                 eventHandled = true;
1116                                                         }
1117                                                         break;
1118 #endif
1119                                         }
1120                                         break;
1121                                 }
1122 #ifdef WITH_INPUT_IME
1123                                 ////////////////////////////////////////////////////////////////////////
1124                                 // IME events, processed, read more in GHOST_IME.h
1125                                 ////////////////////////////////////////////////////////////////////////
1126                                 case WM_IME_SETCONTEXT:
1127                                 {
1128                                         GHOST_ImeWin32 *ime = window->getImeInput();
1129                                         ime->SetInputLanguage();
1130                                         ime->CreateImeWindow(hwnd);
1131                                         ime->CleanupComposition(hwnd);
1132                                         ime->CheckFirst(hwnd);
1133                                         break;
1134                                 }
1135                                 case WM_IME_STARTCOMPOSITION:
1136                                 {
1137                                         GHOST_ImeWin32 *ime = window->getImeInput();
1138                                         eventHandled = true;
1139                                         /* remove input event before start comp event, avoid redundant input */
1140                                         eventManager->removeTypeEvents(GHOST_kEventKeyDown, window);
1141                                         ime->CreateImeWindow(hwnd);
1142                                         ime->ResetComposition(hwnd);
1143                                         event = processImeEvent(
1144                                                 GHOST_kEventImeCompositionStart,
1145                                                 window,
1146                                                 &ime->eventImeData);
1147                                         break;
1148                                 }
1149                                 case WM_IME_COMPOSITION:
1150                                 {
1151                                         GHOST_ImeWin32 *ime = window->getImeInput();
1152                                         eventHandled = true;
1153                                         ime->UpdateImeWindow(hwnd);
1154                                         ime->UpdateInfo(hwnd);
1155                                         if (ime->eventImeData.result_len) {
1156                                                 /* remove redundant IME event */
1157                                                 eventManager->removeTypeEvents(GHOST_kEventImeComposition, window);
1158                                         }
1159                                         event = processImeEvent(
1160                                                 GHOST_kEventImeComposition,
1161                                                 window,
1162                                                 &ime->eventImeData);
1163                                         break;
1164                                 }
1165                                 case WM_IME_ENDCOMPOSITION:
1166                                 {
1167                                         GHOST_ImeWin32 *ime = window->getImeInput();
1168                                         eventHandled = true;
1169                                         /* remove input event after end comp event, avoid redundant input */
1170                                         eventManager->removeTypeEvents(GHOST_kEventKeyDown, window);
1171                                         ime->ResetComposition(hwnd);
1172                                         ime->DestroyImeWindow(hwnd);
1173                                         event = processImeEvent(
1174                                                 GHOST_kEventImeCompositionEnd,
1175                                                 window,
1176                                                 &ime->eventImeData);
1177                                         break;
1178                                 }
1179 #endif /* WITH_INPUT_IME */
1180                                 ////////////////////////////////////////////////////////////////////////
1181                                 // Keyboard events, ignored
1182                                 ////////////////////////////////////////////////////////////////////////
1183                                 case WM_KEYDOWN:
1184                                 case WM_SYSKEYDOWN:
1185                                 case WM_KEYUP:
1186                                 case WM_SYSKEYUP:
1187                                 /* These functions were replaced by WM_INPUT*/
1188                                 case WM_CHAR:
1189                                 /* The WM_CHAR message is posted to the window with the keyboard focus when
1190                                  * a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR
1191                                  * contains the character code of the key that was pressed.
1192                                  */
1193                                 case WM_DEADCHAR:
1194                                         /* The WM_DEADCHAR message is posted to the window with the keyboard focus when a
1195                                          * WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR
1196                                          * specifies a character code generated by a dead key. A dead key is a key that
1197                                          * generates a character, such as the umlaut (double-dot), that is combined with
1198                                          * another character to form a composite character. For example, the umlaut-O
1199                                          * character (Ö) is generated by typing the dead key for the umlaut character, and
1200                                          * then typing the O key.
1201                                          */
1202                                         break;
1203                                 case WM_SYSDEADCHAR:
1204                                 /* The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when
1205                                  * a WM_SYSKEYDOWN message is translated by the TranslateMessage function.
1206                                  * WM_SYSDEADCHAR specifies the character code of a system dead key - that is,
1207                                  * a dead key that is pressed while holding down the alt key.
1208                                  */
1209                                 case WM_SYSCHAR:
1210                                         /* The WM_SYSCHAR message is sent to the window with the keyboard focus when
1211                                          * a WM_SYSCHAR message is translated by the TranslateMessage function.
1212                                          * WM_SYSCHAR specifies the character code of a dead key - that is,
1213                                          * a dead key that is pressed while holding down the alt key.
1214                                          * To prevent the sound, DefWindowProc must be avoided by return
1215                                          */
1216                                         break;
1217                                 case WM_SYSCOMMAND:
1218                                         /* The WM_SYSCHAR message is sent to the window when system commands such as
1219                                          * maximize, minimize  or close the window are triggered. Also it is sent when ALT
1220                                          * button is press for menu. To prevent this we must return preventing DefWindowProc.
1221                                          */
1222                                         if (wParam == SC_KEYMENU) {
1223                                                 eventHandled = true;
1224                                         }
1225                                         break;
1226                                 ////////////////////////////////////////////////////////////////////////
1227                                 // Tablet events, processed
1228                                 ////////////////////////////////////////////////////////////////////////
1229                                 case WT_PACKET:
1230                                         window->processWin32TabletEvent(wParam, lParam);
1231                                         break;
1232                                 case WT_CSRCHANGE:
1233                                 case WT_PROXIMITY:
1234                                         window->processWin32TabletInitEvent();
1235                                         break;
1236                                 ////////////////////////////////////////////////////////////////////////
1237                                 // Mouse events, processed
1238                                 ////////////////////////////////////////////////////////////////////////
1239                                 case WM_LBUTTONDOWN:
1240                                         window->registerMouseClickEvent(0);
1241                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskLeft);
1242                                         break;
1243                                 case WM_MBUTTONDOWN:
1244                                         window->registerMouseClickEvent(0);
1245                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskMiddle);
1246                                         break;
1247                                 case WM_RBUTTONDOWN:
1248                                         window->registerMouseClickEvent(0);
1249                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskRight);
1250                                         break;
1251                                 case WM_XBUTTONDOWN:
1252                                         window->registerMouseClickEvent(0);
1253                                         if ((short) HIWORD(wParam) == XBUTTON1) {
1254                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton4);
1255                                         }
1256                                         else if ((short) HIWORD(wParam) == XBUTTON2) {
1257                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton5);
1258                                         }
1259                                         break;
1260                                 case WM_LBUTTONUP:
1261                                         window->registerMouseClickEvent(1);
1262                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskLeft);
1263                                         break;
1264                                 case WM_MBUTTONUP:
1265                                         window->registerMouseClickEvent(1);
1266                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskMiddle);
1267                                         break;
1268                                 case WM_RBUTTONUP:
1269                                         window->registerMouseClickEvent(1);
1270                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskRight);
1271                                         break;
1272                                 case WM_XBUTTONUP:
1273                                         window->registerMouseClickEvent(1);
1274                                         if ((short) HIWORD(wParam) == XBUTTON1) {
1275                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton4);
1276                                         }
1277                                         else if ((short) HIWORD(wParam) == XBUTTON2) {
1278                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton5);
1279                                         }
1280                                         break;
1281                                 case WM_MOUSEMOVE:
1282                                         event = processCursorEvent(GHOST_kEventCursorMove, window);
1283                                         break;
1284                                 case WM_MOUSEWHEEL:
1285                                 {
1286                                         /* The WM_MOUSEWHEEL message is sent to the focus window
1287                                          * when the mouse wheel is rotated. The DefWindowProc
1288                                          * function propagates the message to the window's parent.
1289                                          * There should be no internal forwarding of the message,
1290                                          * since DefWindowProc propagates it up the parent chain
1291                                          * until it finds a window that processes it.
1292                                          */
1293
1294                                         /* Get the window under the mouse and send event to its queue. */
1295                                         POINT mouse_pos = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
1296                                         HWND mouse_hwnd = ChildWindowFromPoint(HWND_DESKTOP, mouse_pos);
1297                                         GHOST_WindowWin32 *mouse_window = (GHOST_WindowWin32 *)::GetWindowLongPtr(mouse_hwnd, GWLP_USERDATA);
1298
1299                                         processWheelEvent(mouse_window ? mouse_window : window , wParam, lParam);
1300                                         eventHandled = true;
1301 #ifdef BROKEN_PEEK_TOUCHPAD
1302                                         PostMessage(hwnd, WM_USER, 0, 0);
1303 #endif
1304                                         break;
1305                                 }
1306                                 case WM_SETCURSOR:
1307                                         /* The WM_SETCURSOR message is sent to a window if the mouse causes the cursor
1308                                          * to move within a window and mouse input is not captured.
1309                                          * This means we have to set the cursor shape every time the mouse moves!
1310                                          * The DefWindowProc function uses this message to set the cursor to an
1311                                          * arrow if it is not in the client area.
1312                                          */
1313                                         if (LOWORD(lParam) == HTCLIENT) {
1314                                                 // Load the current cursor
1315                                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
1316                                                 // Bypass call to DefWindowProc
1317                                                 return 0;
1318                                         }
1319                                         else {
1320                                                 // Outside of client area show standard cursor
1321                                                 window->loadCursor(true, GHOST_kStandardCursorDefault);
1322                                         }
1323                                         break;
1324
1325                                 ////////////////////////////////////////////////////////////////////////
1326                                 // Mouse events, ignored
1327                                 ////////////////////////////////////////////////////////////////////////
1328                                 case WM_NCMOUSEMOVE:
1329                                 /* The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved
1330                                  * within the nonclient area of the window. This message is posted to the window
1331                                  * that contains the cursor. If a window has captured the mouse, this message is not posted.
1332                                  */
1333                                 case WM_NCHITTEST:
1334                                         /* The WM_NCHITTEST message is sent to a window when the cursor moves, or
1335                                          * when a mouse button is pressed or released. If the mouse is not captured,
1336                                          * the message is sent to the window beneath the cursor. Otherwise, the message
1337                                          * is sent to the window that has captured the mouse.
1338                                          */
1339                                         break;
1340
1341                                 ////////////////////////////////////////////////////////////////////////
1342                                 // Window events, processed
1343                                 ////////////////////////////////////////////////////////////////////////
1344                                 case WM_CLOSE:
1345                                         /* The WM_CLOSE message is sent as a signal that a window or an application should terminate. */
1346                                         event = processWindowEvent(GHOST_kEventWindowClose, window);
1347                                         break;
1348                                 case WM_ACTIVATE:
1349                                         /* The WM_ACTIVATE message is sent to both the window being activated and the window being
1350                                          * deactivated. If the windows use the same input queue, the message is sent synchronously,
1351                                          * first to the window procedure of the top-level window being deactivated, then to the window
1352                                          * procedure of the top-level window being activated. If the windows use different input queues,
1353                                          * the message is sent asynchronously, so the window is activated immediately.
1354                                          */
1355                                 {
1356                                         GHOST_ModifierKeys modifiers;
1357                                         modifiers.clear();
1358                                         system->storeModifierKeys(modifiers);
1359                                         system->m_wheelDeltaAccum = 0;
1360                                         event = processWindowEvent(LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
1361                                         /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
1362                                          * will not be dispatched to OUR active window if we minimize one of OUR windows. */
1363                                         if (LOWORD(wParam) == WA_INACTIVE)
1364                                                 window->lostMouseCapture();
1365                                         window->processWin32TabletActivateEvent(GET_WM_ACTIVATE_STATE(wParam, lParam));
1366                                         lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
1367                                         break;
1368                                 }
1369                                 case WM_ENTERSIZEMOVE:
1370                                         /* The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving
1371                                          * or sizing modal loop. The window enters the moving or sizing modal loop when the user
1372                                          * clicks the window's title bar or sizing border, or when the window passes the
1373                                          * WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the
1374                                          * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when
1375                                          * DefWindowProc returns.
1376                                          */
1377                                         window->m_inLiveResize = 1;
1378                                         break;
1379                                 case WM_EXITSIZEMOVE:
1380                                         window->m_inLiveResize = 0;
1381                                         break;
1382                                 case WM_PAINT:
1383                                         /* An application sends the WM_PAINT message when the system or another application
1384                                          * makes a request to paint a portion of an application's window. The message is sent
1385                                          * when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage
1386                                          * function when the application obtains a WM_PAINT message by using the GetMessage or
1387                                          * PeekMessage function.
1388                                          */
1389                                         if (!window->m_inLiveResize) {
1390                                                 event = processWindowEvent(GHOST_kEventWindowUpdate, window);
1391                                                 ::ValidateRect(hwnd, NULL);
1392                                         }
1393                                         else {
1394                                                 eventHandled = true;
1395                                         }
1396                                         break;
1397                                 case WM_GETMINMAXINFO:
1398                                         /* The WM_GETMINMAXINFO message is sent to a window when the size or
1399                                          * position of the window is about to change. An application can use
1400                                          * this message to override the window's default maximized size and
1401                                          * position, or its default minimum or maximum tracking size.
1402                                          */
1403                                         processMinMaxInfo((MINMAXINFO *) lParam);
1404                                         /* Let DefWindowProc handle it. */
1405                                         break;
1406                                 case WM_SIZING:
1407                                 case WM_SIZE:
1408                                         /* The WM_SIZE message is sent to a window after its size has changed.
1409                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the
1410                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1411                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED
1412                                          * message without calling DefWindowProc.
1413                                          */
1414                                         /* we get first WM_SIZE before we fully init. So, do not dispatch before we continiously resizng */
1415                                         if (window->m_inLiveResize) {
1416                                                 system->pushEvent(processWindowEvent(GHOST_kEventWindowSize, window));
1417                                                 system->dispatchEvents();
1418                                         }
1419                                         else {
1420                                                 event = processWindowEvent(GHOST_kEventWindowSize, window);
1421                                         }
1422                                         break;
1423                                 case WM_CAPTURECHANGED:
1424                                         window->lostMouseCapture();
1425                                         break;
1426                                 case WM_MOVING:
1427                                         /* The WM_MOVING message is sent to a window that the user is moving. By processing
1428                                          * this message, an application can monitor the size and position of the drag rectangle
1429                                          * and, if needed, change its size or position.
1430                                          */
1431                                 case WM_MOVE:
1432                                         /* The WM_SIZE and WM_MOVE messages are not sent if an application handles the
1433                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1434                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED
1435                                          * message without calling DefWindowProc.
1436                                          */
1437                                         /* see WM_SIZE comment*/
1438                                         if (window->m_inLiveResize) {
1439                                                 system->pushEvent(processWindowEvent(GHOST_kEventWindowMove, window));
1440                                                 system->dispatchEvents();
1441                                         }
1442                                         else {
1443                                                 event = processWindowEvent(GHOST_kEventWindowMove, window);
1444                                         }
1445
1446                                         break;
1447                                 case WM_DPICHANGED:
1448                                         /* The WM_DPICHANGED message is sent when the effective dots per inch (dpi) for a window has changed.
1449                                         * The DPI is the scale factor for a window. There are multiple events that can cause the DPI to
1450                                         * change such as when the window is moved to a monitor with a different DPI.
1451                                         */
1452                                         {
1453                                                 WORD newYAxisDPI = HIWORD(wParam);
1454                                                 WORD newXAxisDPI = LOWORD(wParam);
1455                                                 // The suggested new size and position of the window.
1456                                                 RECT* const suggestedWindowRect = (RECT*)lParam;
1457
1458                                                 // Push DPI change event first
1459                                                 system->pushEvent(processWindowEvent(GHOST_kEventWindowDPIHintChanged, window));
1460                                                 system->dispatchEvents();
1461                                                 eventHandled = true;
1462
1463                                                 // Then move and resize window
1464                                                 SetWindowPos(hwnd,
1465                                                         NULL,
1466                                                         suggestedWindowRect->left,
1467                                                         suggestedWindowRect->top,
1468                                                         suggestedWindowRect->right - suggestedWindowRect->left,
1469                                                         suggestedWindowRect->bottom - suggestedWindowRect->top,
1470                                                         SWP_NOZORDER | SWP_NOACTIVATE);
1471                                         }
1472                                         break;
1473                                 ////////////////////////////////////////////////////////////////////////
1474                                 // Window events, ignored
1475                                 ////////////////////////////////////////////////////////////////////////
1476                                 case WM_WINDOWPOSCHANGED:
1477                                 /* The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place
1478                                  * in the Z order has changed as a result of a call to the SetWindowPos function or
1479                                  * another window-management function.
1480                                  * The WM_SIZE and WM_MOVE messages are not sent if an application handles the
1481                                  * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1482                                  * to perform any move or size change processing during the WM_WINDOWPOSCHANGED
1483                                  * message without calling DefWindowProc.
1484                                  */
1485                                 case WM_ERASEBKGND:
1486                                 /* An application sends the WM_ERASEBKGND message when the window background must be
1487                                  * erased (for example, when a window is resized). The message is sent to prepare an
1488                                  * invalidated portion of a window for painting.
1489                                  */
1490                                 case WM_NCPAINT:
1491                                 /* An application sends the WM_NCPAINT message to a window when its frame must be painted. */
1492                                 case WM_NCACTIVATE:
1493                                 /* The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed
1494                                  * to indicate an active or inactive state.
1495                                  */
1496                                 case WM_DESTROY:
1497                                 /* The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window
1498                                  * procedure of the window being destroyed after the window is removed from the screen.
1499                                  * This message is sent first to the window being destroyed and then to the child windows
1500                                  * (if any) as they are destroyed. During the processing of the message, it can be assumed
1501                                  * that all child windows still exist.
1502                                  */
1503                                 case WM_NCDESTROY:
1504                                         /* The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The
1505                                          * DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY
1506                                          * message. WM_DESTROY is used to free the allocated memory object associated with the window.
1507                                          */
1508                                         break;
1509                                 case WM_KILLFOCUS:
1510                                         /* The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus.
1511                                          * We want to prevent this if a window is still active and it loses focus to nowhere*/
1512                                         if (!wParam && hwnd == ::GetActiveWindow())
1513                                                 ::SetFocus(hwnd);
1514                                 case WM_SHOWWINDOW:
1515                                 /* The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown. */
1516                                 case WM_WINDOWPOSCHANGING:
1517                                 /* The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in
1518                                  * the Z order is about to change as a result of a call to the SetWindowPos function or
1519                                  * another window-management function.
1520                                  */
1521                                 case WM_SETFOCUS:
1522                                 /* The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus. */
1523                                         break;
1524                                 ////////////////////////////////////////////////////////////////////////
1525                                 // Other events
1526                                 ////////////////////////////////////////////////////////////////////////
1527                                 case WM_GETTEXT:
1528                                 /* An application sends a WM_GETTEXT message to copy the text that
1529                                  * corresponds to a window into a buffer provided by the caller.
1530                                  */
1531                                 case WM_ACTIVATEAPP:
1532                                 /* The WM_ACTIVATEAPP message is sent when a window belonging to a
1533                                  * different application than the active window is about to be activated.
1534                                  * The message is sent to the application whose window is being activated
1535                                  * and to the application whose window is being deactivated.
1536                                  */
1537                                 case WM_TIMER:
1538                                         /* The WIN32 docs say:
1539                                          * The WM_TIMER message is posted to the installing thread's message queue
1540                                          * when a timer expires. You can process the message by providing a WM_TIMER
1541                                          * case in the window procedure. Otherwise, the default window procedure will
1542                                          * call the TimerProc callback function specified in the call to the SetTimer
1543                                          * function used to install the timer.
1544                                          *
1545                                          * In GHOST, we let DefWindowProc call the timer callback.
1546                                          */
1547                                         break;
1548
1549                         }
1550                 }
1551                 else {
1552                         // Event found for a window before the pointer to the class has been set.
1553                         GHOST_PRINT("GHOST_SystemWin32::wndProc: GHOST window event before creation\n");
1554                         /* These are events we typically miss at this point:
1555                          * WM_GETMINMAXINFO     0x24
1556                          * WM_NCCREATE                  0x81
1557                          * WM_NCCALCSIZE                0x83
1558                          * WM_CREATE                    0x01
1559                          * We let DefWindowProc do the work.
1560                          */
1561                 }
1562         }
1563         else {
1564                 // Events without valid hwnd
1565                 GHOST_PRINT("GHOST_SystemWin32::wndProc: event without window\n");
1566         }
1567
1568         if (event) {
1569                 system->pushEvent(event);
1570                 eventHandled = true;
1571         }
1572
1573         if (!eventHandled)
1574                 lResult = ::DefWindowProcW(hwnd, msg, wParam, lParam);
1575
1576         return lResult;
1577 }
1578
1579 GHOST_TUns8 *GHOST_SystemWin32::getClipboard(bool selection) const
1580 {
1581         char *temp_buff;
1582
1583         if (IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL) ) {
1584                 wchar_t *buffer;
1585                 HANDLE hData = GetClipboardData(CF_UNICODETEXT);
1586                 if (hData == NULL) {
1587                         CloseClipboard();
1588                         return NULL;
1589                 }
1590                 buffer = (wchar_t *)GlobalLock(hData);
1591                 if (!buffer) {
1592                         CloseClipboard();
1593                         return NULL;
1594                 }
1595
1596                 temp_buff = alloc_utf_8_from_16(buffer, 0);
1597
1598                 /* Buffer mustn't be accessed after CloseClipboard
1599                  * it would like accessing free-d memory */
1600                 GlobalUnlock(hData);
1601                 CloseClipboard();
1602
1603                 return (GHOST_TUns8 *)temp_buff;
1604         }
1605         else if (IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL) ) {
1606                 char *buffer;
1607                 size_t len = 0;
1608                 HANDLE hData = GetClipboardData(CF_TEXT);
1609                 if (hData == NULL) {
1610                         CloseClipboard();
1611                         return NULL;
1612                 }
1613                 buffer = (char *)GlobalLock(hData);
1614                 if (!buffer) {
1615                         CloseClipboard();
1616                         return NULL;
1617                 }
1618
1619                 len = strlen(buffer);
1620                 temp_buff = (char *) malloc(len + 1);
1621                 strncpy(temp_buff, buffer, len);
1622                 temp_buff[len] = '\0';
1623
1624                 /* Buffer mustn't be accessed after CloseClipboard
1625                  * it would like accessing free-d memory */
1626                 GlobalUnlock(hData);
1627                 CloseClipboard();
1628
1629                 return (GHOST_TUns8 *)temp_buff;
1630         }
1631         else {
1632                 return NULL;
1633         }
1634 }
1635
1636 void GHOST_SystemWin32::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1637 {
1638         if (selection) {return; } // for copying the selection, used on X11
1639
1640         if (OpenClipboard(NULL)) {
1641                 HLOCAL clipbuffer;
1642                 wchar_t *data;
1643
1644                 if (buffer) {
1645                         size_t len = count_utf_16_from_8(buffer);
1646                         EmptyClipboard();
1647
1648                         clipbuffer = LocalAlloc(LMEM_FIXED, sizeof(wchar_t) * len);
1649                         data = (wchar_t *)GlobalLock(clipbuffer);
1650
1651                         conv_utf_8_to_16(buffer, data, len);
1652
1653                         LocalUnlock(clipbuffer);
1654                         SetClipboardData(CF_UNICODETEXT, clipbuffer);
1655                 }
1656                 CloseClipboard();
1657         }
1658         else {
1659                 return;
1660         }
1661 }
1662
1663 static DWORD GetParentProcessID(void)
1664 {
1665         HANDLE snapshot;
1666         PROCESSENTRY32 pe32 = {0};
1667         DWORD ppid = 0, pid = GetCurrentProcessId();
1668         snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
1669         if (snapshot == INVALID_HANDLE_VALUE) {
1670                 return -1;
1671         }
1672         pe32.dwSize = sizeof( pe32 );
1673         if (!Process32First(snapshot, &pe32)) {
1674                 CloseHandle(snapshot);
1675                 return -1;
1676         }
1677         do {
1678                 if (pe32.th32ProcessID == pid) {
1679                         ppid = pe32.th32ParentProcessID;
1680                         break;
1681                 }
1682         } while (Process32Next(snapshot, &pe32));
1683         CloseHandle(snapshot);
1684         return ppid;
1685 }
1686
1687 static bool getProcessName(int pid, char *buffer, int max_len)
1688 {
1689         bool result = false;
1690         HANDLE handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
1691                                     FALSE, pid);
1692         if (handle) {
1693                 GetModuleFileNameEx(handle, 0, buffer, max_len);
1694                 result = true;
1695         }
1696         CloseHandle(handle);
1697         return result;
1698 }
1699
1700 static bool isStartedFromCommandPrompt()
1701 {
1702         HWND hwnd = GetConsoleWindow();
1703
1704         if (hwnd) {
1705                 DWORD pid = (DWORD)-1;
1706                 DWORD ppid = GetParentProcessID();
1707                 char parent_name[MAX_PATH];
1708                 bool start_from_launcher = false;
1709
1710                 GetWindowThreadProcessId(hwnd, &pid);
1711                 if (getProcessName(ppid, parent_name, sizeof(parent_name))) {
1712                         char *filename = strrchr(parent_name, '\\');
1713                         if (filename != NULL) {
1714                                 start_from_launcher = strstr(filename, "blender.exe") != NULL;
1715                         }
1716                 }
1717
1718                 /* When we're starting from a wrapper we need to compare with parent process ID. */
1719                 if (pid == (start_from_launcher ? ppid : GetCurrentProcessId()))
1720                         return true;
1721         }
1722
1723         return false;
1724 }
1725
1726 int GHOST_SystemWin32::toggleConsole(int action)
1727 {
1728         switch (action) {
1729                 case 3: // startup: hide if not started from command prompt
1730                 {
1731                         if (isStartedFromCommandPrompt()) {
1732                                 ShowWindow(GetConsoleWindow(), SW_HIDE);
1733                                 m_consoleStatus = 0;
1734                         }
1735                         break;
1736                 }
1737                 case 0: // hide
1738                         ShowWindow(GetConsoleWindow(), SW_HIDE);
1739                         m_consoleStatus = 0;
1740                         break;
1741                 case 1: // show
1742                         ShowWindow(GetConsoleWindow(), SW_SHOW);
1743                         m_consoleStatus = 1;
1744                         break;
1745                 case 2: // toggle
1746                         ShowWindow(GetConsoleWindow(), m_consoleStatus ? SW_HIDE : SW_SHOW);
1747                         m_consoleStatus = !m_consoleStatus;
1748                         break;
1749         }
1750
1751
1752         return m_consoleStatus;
1753 }
1754
1755 int GHOST_SystemWin32::confirmQuit(GHOST_IWindow *window) const
1756 {
1757         return (MessageBox(window ? ((GHOST_WindowWin32 *)window)->getHWND() : 0, "Some changes have not been saved.\nDo you really want to quit?",
1758                            "Exit Blender", MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST) == IDOK);
1759 }