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