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