b00ff690cfa50376dceddefa3b05a079752a7349
[blender.git] / intern / ghost / intern / GHOST_SystemWin32.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file ghost/intern/GHOST_SystemWin32.cpp
29  *  \ingroup GHOST
30  */
31
32
33 /**
34
35  * Copyright (C) 2001 NaN Technologies B.V.
36  * @author      Maarten Gribnau
37  * @date        May 7, 2001
38  */
39
40 #ifdef BF_GHOST_DEBUG
41 #include <iostream>
42 #endif
43
44 #include <stdio.h> // [mce] temporary debug, remove soon!
45
46 #include "GHOST_SystemWin32.h"
47 #include "GHOST_EventDragnDrop.h"
48
49 #ifndef _WIN32_IE
50 #define _WIN32_IE 0x0501 /* shipped before XP, so doesn't impose additional requirements */
51 #endif
52 #include <shlobj.h>
53 #include <tlhelp32.h>
54
55 // win64 doesn't define GWL_USERDATA
56 #ifdef WIN32
57 #ifndef GWL_USERDATA
58 #define GWL_USERDATA GWLP_USERDATA
59 #define GWL_WNDPROC GWLP_WNDPROC 
60 #endif
61 #endif
62
63 #include "utfconv.h"
64
65 #include "GHOST_DisplayManagerWin32.h"
66 #include "GHOST_EventButton.h"
67 #include "GHOST_EventCursor.h"
68 #include "GHOST_EventKey.h"
69 #include "GHOST_EventWheel.h"
70 #include "GHOST_TimerTask.h"
71 #include "GHOST_TimerManager.h"
72 #include "GHOST_WindowManager.h"
73 #include "GHOST_WindowWin32.h"
74
75 #ifdef WITH_INPUT_NDOF
76 #include "GHOST_NDOFManagerWin32.h"
77 #endif
78
79 // Key code values not found in winuser.h
80 #ifndef VK_MINUS
81 #define VK_MINUS 0xBD
82 #endif // VK_MINUS
83 #ifndef VK_SEMICOLON
84 #define VK_SEMICOLON 0xBA
85 #endif // VK_SEMICOLON
86 #ifndef VK_PERIOD
87 #define VK_PERIOD 0xBE
88 #endif // VK_PERIOD
89 #ifndef VK_COMMA
90 #define VK_COMMA 0xBC
91 #endif // VK_COMMA
92 #ifndef VK_QUOTE
93 #define VK_QUOTE 0xDE
94 #endif // VK_QUOTE
95 #ifndef VK_BACK_QUOTE
96 #define VK_BACK_QUOTE 0xC0
97 #endif // VK_BACK_QUOTE
98 #ifndef VK_SLASH
99 #define VK_SLASH 0xBF
100 #endif // VK_SLASH
101 #ifndef VK_BACK_SLASH
102 #define VK_BACK_SLASH 0xDC
103 #endif // VK_BACK_SLASH
104 #ifndef VK_EQUALS
105 #define VK_EQUALS 0xBB
106 #endif // VK_EQUALS
107 #ifndef VK_OPEN_BRACKET
108 #define VK_OPEN_BRACKET 0xDB
109 #endif // VK_OPEN_BRACKET
110 #ifndef VK_CLOSE_BRACKET
111 #define VK_CLOSE_BRACKET 0xDD
112 #endif // VK_CLOSE_BRACKET
113 #ifndef VK_GR_LESS
114 #define VK_GR_LESS 0xE2
115 #endif // VK_GR_LESS
116
117 #ifndef VK_MEDIA_NEXT_TRACK
118 #define VK_MEDIA_NEXT_TRACK     0xB0
119 #endif // VK_MEDIA_NEXT_TRACK
120 #ifndef VK_MEDIA_PREV_TRACK
121 #define VK_MEDIA_PREV_TRACK     0xB1
122 #endif // VK_MEDIA_PREV_TRACK
123 #ifndef VK_MEDIA_STOP
124 #define VK_MEDIA_STOP   0xB2
125 #endif // VK_MEDIA_STOP
126 #ifndef VK_MEDIA_PLAY_PAUSE
127 #define VK_MEDIA_PLAY_PAUSE     0xB3
128 #endif // VK_MEDIA_PLAY_PAUSE
129
130 static void initRawInput()
131 {
132 #ifdef WITH_INPUT_NDOF
133 #define DEVICE_COUNT 2
134 #else
135 #define DEVICE_COUNT 1
136 #endif
137
138         RAWINPUTDEVICE devices[DEVICE_COUNT];
139         memset(devices, 0, DEVICE_COUNT * sizeof(RAWINPUTDEVICE));
140
141         // Initiates WM_INPUT messages from keyboard
142         // That way GHOST can retrieve true keys
143         devices[0].usUsagePage = 0x01;
144         devices[0].usUsage = 0x06; /* http://msdn.microsoft.com/en-us/windows/hardware/gg487473.aspx */
145
146 #ifdef WITH_INPUT_NDOF
147         // multi-axis mouse (SpaceNavigator, etc.)
148         devices[1].usUsagePage = 0x01;
149         devices[1].usUsage = 0x08;
150 #endif
151
152         if (RegisterRawInputDevices(devices, DEVICE_COUNT, sizeof(RAWINPUTDEVICE)))
153                 ; // yay!
154         else
155                 printf("could not register for RawInput: %d\n", (int)GetLastError());
156
157 #undef DEVICE_COUNT
158 }
159
160 GHOST_SystemWin32::GHOST_SystemWin32()
161 : m_hasPerformanceCounter(false), m_freq(0), m_start(0)
162 {
163         m_displayManager = new GHOST_DisplayManagerWin32 ();
164         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::GHOST_SystemWin32(): m_displayManager==0\n");
165         m_displayManager->initialize();
166
167         m_consoleStatus = 1;
168
169         // Check if current keyboard layout uses AltGr and save keylayout ID for
170         // specialized handling if keys like VK_OEM_*. I.e. french keylayout
171         // generates VK_OEM_8 for their exclamation key (key left of right shift)
172         this->handleKeyboardChange();
173         // Require COM for GHOST_DropTargetWin32 created in GHOST_WindowWin32.
174         OleInitialize(0);
175
176 #ifdef WITH_INPUT_NDOF
177         m_ndofManager = new GHOST_NDOFManagerWin32(*this);
178 #endif
179 }
180
181 GHOST_SystemWin32::~GHOST_SystemWin32()
182 {
183         // Shutdown COM
184         OleUninitialize();
185         toggleConsole(1);
186 }
187
188
189 GHOST_TUns64 GHOST_SystemWin32::getMilliSeconds() const
190 {
191         // Hardware does not support high resolution timers. We will use GetTickCount instead then.
192         if (!m_hasPerformanceCounter) {
193                 return ::GetTickCount();
194         }
195
196         // Retrieve current count
197         __int64 count = 0;
198         ::QueryPerformanceCounter((LARGE_INTEGER*)&count);
199
200         // Calculate the time passed since system initialization.
201         __int64 delta = 1000*(count-m_start);
202
203         GHOST_TUns64 t = (GHOST_TUns64)(delta/m_freq);
204         return t; 
205 }
206
207
208 GHOST_TUns8 GHOST_SystemWin32::getNumDisplays() const
209 {
210         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::getNumDisplays(): m_displayManager==0\n");
211         GHOST_TUns8 numDisplays;
212         m_displayManager->getNumDisplays(numDisplays);
213         return numDisplays;
214 }
215
216
217 void GHOST_SystemWin32::getMainDisplayDimensions(GHOST_TUns32& width, GHOST_TUns32& height) const
218 {
219         width = ::GetSystemMetrics(SM_CXSCREEN);
220         height= ::GetSystemMetrics(SM_CYSCREEN);
221 }
222
223
224 GHOST_IWindow* GHOST_SystemWin32::createWindow(
225         const STR_String& title, 
226         GHOST_TInt32 left, GHOST_TInt32 top, GHOST_TUns32 width, GHOST_TUns32 height,
227         GHOST_TWindowState state, GHOST_TDrawingContextType type,
228         bool stereoVisual, const GHOST_TUns16 numOfAASamples, const GHOST_TEmbedderWindowID parentWindow )
229 {
230         GHOST_Window* window = 0;
231         window = new GHOST_WindowWin32 (this, title, left, top, width, height, state, type, stereoVisual, numOfAASamples, parentWindow);
232         if (window) {
233                 if (window->getValid()) {
234                         // Store the pointer to the window
235 //                      if (state != GHOST_kWindowStateFullScreen) {
236                                 m_windowManager->addWindow(window);
237                                 m_windowManager->setActiveWindow(window);
238 //                      }
239                 }
240                 else {
241
242                         // Invalid parent window hwnd
243                         if (((GHOST_WindowWin32*)window)->getNextWindow() == NULL) {
244                                 delete window;
245                                 window = 0;
246                                 return window;
247                         }
248
249                         // An invalid window could be one that was used to test for AA
250                         window = ((GHOST_WindowWin32*)window)->getNextWindow();
251                         
252                         // If another window is found, let the wm know about that one, but not the old one
253                         if (window->getValid()) {
254                                 m_windowManager->addWindow(window);
255                         }
256                         else {
257                                 delete window;
258                                 window = 0;
259                         }
260
261                 }
262         }
263         return window;
264 }
265
266
267 bool GHOST_SystemWin32::processEvents(bool waitForEvent)
268 {
269         MSG msg;
270         bool anyProcessed = false;
271
272         do {
273                 GHOST_TimerManager* timerMgr = getTimerManager();
274
275                 if (waitForEvent && !::PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE)) {
276 #if 1
277                         ::Sleep(1);
278 #else
279                         GHOST_TUns64 next = timerMgr->nextFireTime();
280                         GHOST_TInt64 maxSleep = next - getMilliSeconds();
281                         
282                         if (next == GHOST_kFireTimeNever) {
283                                 ::WaitMessage();
284                         } else if(maxSleep >= 0.0) {
285                                 ::SetTimer(NULL, 0, maxSleep, NULL);
286                                 ::WaitMessage();
287                                 ::KillTimer(NULL, 0);
288                         }
289 #endif
290                 }
291
292                 if (timerMgr->fireTimers(getMilliSeconds())) {
293                         anyProcessed = true;
294                 }
295
296                 // Process all the events waiting for us
297                 while (::PeekMessageW(&msg, 0, 0, 0, PM_REMOVE) != 0) {
298                         ::DispatchMessageW(&msg);
299                         anyProcessed = true;
300                 }
301         } while (waitForEvent && !anyProcessed);
302
303         return anyProcessed;
304 }
305
306
307 GHOST_TSuccess GHOST_SystemWin32::getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const
308 {
309         POINT point;
310         if(::GetCursorPos(&point)){
311                 x = point.x;
312                 y = point.y;
313                 return GHOST_kSuccess;
314         }
315         return GHOST_kFailure;
316 }
317
318
319 GHOST_TSuccess GHOST_SystemWin32::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y)
320 {
321         if (!GetActiveWindow())
322                 return GHOST_kFailure;
323         return ::SetCursorPos(x, y) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
324 }
325
326
327 GHOST_TSuccess GHOST_SystemWin32::getModifierKeys(GHOST_ModifierKeys& keys) const
328 {
329         bool down = HIBYTE(::GetKeyState(VK_LSHIFT)) != 0;
330         keys.set(GHOST_kModifierKeyLeftShift, down);
331         down = HIBYTE(::GetKeyState(VK_RSHIFT)) != 0;
332         keys.set(GHOST_kModifierKeyRightShift, down);
333         
334         down = HIBYTE(::GetKeyState(VK_LMENU)) != 0;
335         keys.set(GHOST_kModifierKeyLeftAlt, down);
336         down = HIBYTE(::GetKeyState(VK_RMENU)) != 0;
337         keys.set(GHOST_kModifierKeyRightAlt, down);
338         
339         down = HIBYTE(::GetKeyState(VK_LCONTROL)) != 0;
340         keys.set(GHOST_kModifierKeyLeftControl, down);
341         down = HIBYTE(::GetKeyState(VK_RCONTROL)) != 0;
342         keys.set(GHOST_kModifierKeyRightControl, down);
343         
344         bool lwindown = HIBYTE(::GetKeyState(VK_LWIN)) != 0;
345         bool rwindown = HIBYTE(::GetKeyState(VK_RWIN)) != 0;
346         if(lwindown || rwindown)
347                 keys.set(GHOST_kModifierKeyOS, true);
348         else
349                 keys.set(GHOST_kModifierKeyOS, false);
350         return GHOST_kSuccess;
351 }
352
353
354 GHOST_TSuccess GHOST_SystemWin32::getButtons(GHOST_Buttons& buttons) const
355 {
356         /* Check for swapped buttons (left-handed mouse buttons)
357          * GetAsyncKeyState() will give back the state of the physical mouse buttons.
358          */
359         bool swapped = ::GetSystemMetrics(SM_SWAPBUTTON) == TRUE;
360
361         bool down = HIBYTE(::GetKeyState(VK_LBUTTON)) != 0;
362         buttons.set(swapped ? GHOST_kButtonMaskRight : GHOST_kButtonMaskLeft, down);
363
364         down = HIBYTE(::GetKeyState(VK_MBUTTON)) != 0;
365         buttons.set(GHOST_kButtonMaskMiddle, down);
366
367         down = HIBYTE(::GetKeyState(VK_RBUTTON)) != 0;
368         buttons.set(swapped ? GHOST_kButtonMaskLeft : GHOST_kButtonMaskRight, down);
369         return GHOST_kSuccess;
370 }
371
372
373 GHOST_TSuccess GHOST_SystemWin32::init()
374 {
375         GHOST_TSuccess success = GHOST_System::init();
376         
377         /* Disable scaling on high DPI displays on Vista */
378         HMODULE
379         user32 = ::LoadLibraryA("user32.dll");
380         typedef BOOL (WINAPI * LPFNSETPROCESSDPIAWARE)();
381         LPFNSETPROCESSDPIAWARE SetProcessDPIAware =
382                 (LPFNSETPROCESSDPIAWARE)GetProcAddress(user32, "SetProcessDPIAware");
383         if (SetProcessDPIAware)
384                 SetProcessDPIAware();
385         FreeLibrary(user32);
386         initRawInput();
387
388         // Determine whether this system has a high frequency performance counter. */
389         m_hasPerformanceCounter = ::QueryPerformanceFrequency((LARGE_INTEGER*)&m_freq) == TRUE;
390         if (m_hasPerformanceCounter) {
391                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer available\n")
392                 ::QueryPerformanceCounter((LARGE_INTEGER*)&m_start);
393         }
394         else {
395                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer not available\n")
396         }
397
398         if (success) {
399                 WNDCLASSW wc;
400                 wc.style= CS_HREDRAW | CS_VREDRAW;
401                 wc.lpfnWndProc= s_wndProc;
402                 wc.cbClsExtra= 0;
403                 wc.cbWndExtra= 0;
404                 wc.hInstance= ::GetModuleHandle(0);
405                 wc.hIcon = ::LoadIcon(wc.hInstance, "APPICON");
406                 
407                 if (!wc.hIcon) {
408                         ::LoadIcon(NULL, IDI_APPLICATION);
409                 }
410                 wc.hCursor = ::LoadCursor(0, IDC_ARROW);
411                 wc.hbrBackground= (HBRUSH)::GetStockObject(BLACK_BRUSH);
412                 wc.lpszMenuName = 0;
413                 wc.lpszClassName= L"GHOST_WindowClass";
414
415                 // Use RegisterClassEx for setting small icon
416                 if (::RegisterClassW(&wc) == 0) {
417                         success = GHOST_kFailure;
418                 }
419         }
420         
421         return success;
422 }
423
424
425 GHOST_TSuccess GHOST_SystemWin32::exit()
426 {
427         return GHOST_System::exit();
428 }
429
430 GHOST_TKey GHOST_SystemWin32::hardKey(GHOST_IWindow *window, RAWINPUT const& raw, int * keyDown, char * vk)
431 {
432         GHOST_TKey key = GHOST_kKeyUnknown;
433
434
435         if(!keyDown)
436                 return GHOST_kKeyUnknown;
437
438
439         GHOST_SystemWin32 *system = (GHOST_SystemWin32 *)getSystem();
440
441         GHOST_ModifierKeys modifiers;
442         system->retrieveModifierKeys(modifiers);
443
444         // RI_KEY_BREAK doesn't work for sticky keys release, so we also
445         // check for the up message
446         unsigned int msg = raw.data.keyboard.Message;
447         *keyDown = !(raw.data.keyboard.Flags & RI_KEY_BREAK) && msg != WM_KEYUP && msg != WM_SYSKEYUP;
448
449         key = this->convertKey(window, raw.data.keyboard.VKey, raw.data.keyboard.MakeCode, (raw.data.keyboard.Flags&(RI_KEY_E1|RI_KEY_E0)));
450         
451         // extra handling of modifier keys: don't send repeats out from GHOST
452         if(key >= GHOST_kKeyLeftShift && key <= GHOST_kKeyRightAlt)
453         {
454                 bool changed = false;
455                 GHOST_TModifierKeyMask modifier;
456                 switch(key) {
457                         case GHOST_kKeyLeftShift:
458                                 {
459                                         changed = (modifiers.get(GHOST_kModifierKeyLeftShift) != (bool)*keyDown);
460                                         modifier = GHOST_kModifierKeyLeftShift;
461                                 }
462                                 break;
463                         case GHOST_kKeyRightShift:
464                                 {
465                                         changed = (modifiers.get(GHOST_kModifierKeyRightShift) != (bool)*keyDown);
466                                         modifier = GHOST_kModifierKeyRightShift;
467                                 }
468                                 break;
469                         case GHOST_kKeyLeftControl:
470                                 {
471                                         changed = (modifiers.get(GHOST_kModifierKeyLeftControl) != (bool)*keyDown);
472                                         modifier = GHOST_kModifierKeyLeftControl;
473                                 }
474                                 break;
475                         case GHOST_kKeyRightControl:
476                                 {
477                                         changed = (modifiers.get(GHOST_kModifierKeyRightControl) != (bool)*keyDown);
478                                         modifier = GHOST_kModifierKeyRightControl;
479                                 }
480                                 break;
481                         case GHOST_kKeyLeftAlt:
482                                 {
483                                         changed = (modifiers.get(GHOST_kModifierKeyLeftAlt) != (bool)*keyDown);
484                                         modifier = GHOST_kModifierKeyLeftAlt;
485                                 }
486                                 break;
487                         case GHOST_kKeyRightAlt:
488                                 {
489                                         changed = (modifiers.get(GHOST_kModifierKeyRightAlt) != (bool)*keyDown);
490                                         modifier = GHOST_kModifierKeyRightAlt;
491                                 }
492                                 break;
493                         default: break;
494                 }
495                 
496                 if(changed)
497                 {
498                         modifiers.set(modifier, (bool)*keyDown);
499                         system->storeModifierKeys(modifiers);
500                 }
501                 else
502                 {
503                         key = GHOST_kKeyUnknown;
504                 }
505         }
506         
507
508         if(vk) *vk = raw.data.keyboard.VKey;
509
510         return key;
511 }
512
513 //! note: this function can be extended to include other exotic cases as they arise.
514 // This function was added in response to bug [#25715]
515 GHOST_TKey GHOST_SystemWin32::processSpecialKey(GHOST_IWindow *window, short vKey, short scanCode) const
516 {
517         GHOST_TKey key = GHOST_kKeyUnknown;
518         switch(PRIMARYLANGID(m_langId)) {
519                 case LANG_FRENCH:
520                         if(vKey==VK_OEM_8) key = GHOST_kKeyF13; // oem key; used purely for shortcuts .
521                         break;
522         }
523
524         return key;
525 }
526
527 GHOST_TKey GHOST_SystemWin32::convertKey(GHOST_IWindow *window, short vKey, short scanCode, short extend) const
528 {
529         GHOST_TKey key;
530
531         if ((vKey >= '0') && (vKey <= '9')) {
532                 // VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
533                 key = (GHOST_TKey)(vKey - '0' + GHOST_kKey0);
534         }
535         else if ((vKey >= 'A') && (vKey <= 'Z')) {
536                 // VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
537                 key = (GHOST_TKey)(vKey - 'A' + GHOST_kKeyA);
538         }
539         else if ((vKey >= VK_F1) && (vKey <= VK_F24)) {
540                 key = (GHOST_TKey)(vKey - VK_F1 + GHOST_kKeyF1);
541         }
542         else {
543                 switch (vKey) {
544                 case VK_RETURN:
545                                 key = (extend)?GHOST_kKeyNumpadEnter : GHOST_kKeyEnter; break;
546                         
547                 case VK_BACK:     key = GHOST_kKeyBackSpace;            break;
548                 case VK_TAB:      key = GHOST_kKeyTab;                          break;
549                 case VK_ESCAPE:   key = GHOST_kKeyEsc;                          break;
550                 case VK_SPACE:    key = GHOST_kKeySpace;                        break;
551                 
552                 case VK_INSERT:
553                 case VK_NUMPAD0:
554                         key = (extend) ? GHOST_kKeyInsert : GHOST_kKeyNumpad0;  break;
555                 case VK_END:
556                 case VK_NUMPAD1:        
557                         key = (extend) ? GHOST_kKeyEnd : GHOST_kKeyNumpad1;     break;
558                 case VK_DOWN:
559                 case VK_NUMPAD2:
560                         key = (extend) ? GHOST_kKeyDownArrow : GHOST_kKeyNumpad2;       break;
561                 case VK_NEXT:
562                 case VK_NUMPAD3:
563                         key = (extend) ?  GHOST_kKeyDownPage : GHOST_kKeyNumpad3;       break;
564                 case VK_LEFT:
565                 case VK_NUMPAD4:
566                         key = (extend) ? GHOST_kKeyLeftArrow : GHOST_kKeyNumpad4;       break;
567                 case VK_CLEAR:
568                 case VK_NUMPAD5:
569                         key = (extend) ? GHOST_kKeyUnknown: GHOST_kKeyNumpad5;  break;
570                 case VK_RIGHT:
571                 case VK_NUMPAD6:
572                         key = (extend) ? GHOST_kKeyRightArrow : GHOST_kKeyNumpad6;      break;
573                 case VK_HOME:
574                 case VK_NUMPAD7:
575                         key = (extend) ? GHOST_kKeyHome : GHOST_kKeyNumpad7;    break;
576                 case VK_UP:
577                 case VK_NUMPAD8:
578                         key = (extend) ? GHOST_kKeyUpArrow : GHOST_kKeyNumpad8; break;
579                 case VK_PRIOR:
580                 case VK_NUMPAD9:
581                         key = (extend) ? GHOST_kKeyUpPage : GHOST_kKeyNumpad9;  break;
582                 case VK_DECIMAL:
583                 case VK_DELETE:
584                         key = (extend) ? GHOST_kKeyDelete : GHOST_kKeyNumpadPeriod;     break;
585
586                 case VK_SNAPSHOT: key = GHOST_kKeyPrintScreen;          break;
587                 case VK_PAUSE:    key = GHOST_kKeyPause;                        break;
588                 case VK_MULTIPLY: key = GHOST_kKeyNumpadAsterisk;       break;
589                 case VK_SUBTRACT: key = GHOST_kKeyNumpadMinus;          break;
590                 case VK_DIVIDE:   key = GHOST_kKeyNumpadSlash;          break;
591                 case VK_ADD:      key = GHOST_kKeyNumpadPlus;           break;
592
593                 case VK_SEMICOLON:              key = GHOST_kKeySemicolon;              break;
594                 case VK_EQUALS:                 key = GHOST_kKeyEqual;                  break;
595                 case VK_COMMA:                  key = GHOST_kKeyComma;                  break;
596                 case VK_MINUS:                  key = GHOST_kKeyMinus;                  break;
597                 case VK_PERIOD:                 key = GHOST_kKeyPeriod;                 break;
598                 case VK_SLASH:                  key = GHOST_kKeySlash;                  break;
599                 case VK_BACK_QUOTE:             key = GHOST_kKeyAccentGrave;    break;
600                 case VK_OPEN_BRACKET:   key = GHOST_kKeyLeftBracket;    break;
601                 case VK_BACK_SLASH:             key = GHOST_kKeyBackslash;              break;
602                 case VK_CLOSE_BRACKET:  key = GHOST_kKeyRightBracket;   break;
603                 case VK_QUOTE:                  key = GHOST_kKeyQuote;                  break;
604                 case VK_GR_LESS:                key = GHOST_kKeyGrLess;                 break;
605
606                 case VK_SHIFT:
607                         key = (scanCode == 0x36)? GHOST_kKeyRightShift : GHOST_kKeyLeftShift;
608                         break;
609                 case VK_CONTROL:
610                         key = (extend)? GHOST_kKeyRightControl : GHOST_kKeyLeftControl;
611                         break;
612                 case VK_MENU:
613                         key = (extend)? GHOST_kKeyRightAlt : GHOST_kKeyLeftAlt;
614                         break;
615                 case VK_LWIN:
616                 case VK_RWIN:
617                         key = GHOST_kKeyOS;
618                         break;
619                 case VK_NUMLOCK: key = GHOST_kKeyNumLock; break;
620                 case VK_SCROLL: key = GHOST_kKeyScrollLock; break;
621                 case VK_CAPITAL: key = GHOST_kKeyCapsLock; break;
622                 case VK_OEM_8:
623                         key = ((GHOST_SystemWin32*)getSystem())->processSpecialKey(window, vKey, scanCode);
624                         break;
625                 case VK_MEDIA_PLAY_PAUSE: key = GHOST_kKeyMediaPlay; break;
626                 case VK_MEDIA_STOP: key = GHOST_kKeyMediaStop; break;
627                 case VK_MEDIA_PREV_TRACK: key = GHOST_kKeyMediaFirst; break;
628                 case VK_MEDIA_NEXT_TRACK: key = GHOST_kKeyMediaLast; break;
629                 default:
630                         key = GHOST_kKeyUnknown;
631                         break;
632                 }
633         }
634         
635         return key;
636 }
637
638 GHOST_EventButton* GHOST_SystemWin32::processButtonEvent(GHOST_TEventType type, GHOST_IWindow *window, GHOST_TButtonMask mask)
639 {
640         return new GHOST_EventButton (getSystem()->getMilliSeconds(), type, window, mask);
641 }
642
643
644 GHOST_EventCursor* GHOST_SystemWin32::processCursorEvent(GHOST_TEventType type, GHOST_IWindow *Iwindow)
645 {
646         GHOST_TInt32 x_screen, y_screen;
647         GHOST_SystemWin32 * system = ((GHOST_SystemWin32 * ) getSystem());
648         GHOST_WindowWin32 * window = ( GHOST_WindowWin32 * ) Iwindow;
649         
650         system->getCursorPosition(x_screen, y_screen);
651
652         /* TODO: CHECK IF THIS IS A TABLET EVENT */
653         bool is_tablet = false;
654
655         if (is_tablet == false &&
656             window->getCursorGrabMode() != GHOST_kGrabDisable &&
657             window->getCursorGrabMode() != GHOST_kGrabNormal)
658         {
659                 GHOST_TInt32 x_new= x_screen;
660                 GHOST_TInt32 y_new= y_screen;
661                 GHOST_TInt32 x_accum, y_accum;
662                 GHOST_Rect bounds;
663
664                 /* fallback to window bounds */
665                 if(window->getCursorGrabBounds(bounds)==GHOST_kFailure){
666                         window->getClientBounds(bounds);
667                 }
668
669                 /* could also clamp to screen bounds
670                  * wrap with a window outside the view will fail atm  */
671
672                 bounds.wrapPoint(x_new, y_new, 2); /* offset of one incase blender is at screen bounds */
673
674                 window->getCursorGrabAccum(x_accum, y_accum);
675                 if(x_new != x_screen|| y_new != y_screen) {
676                         /* when wrapping we don't need to add an event because the
677                          * setCursorPosition call will cause a new event after */
678                         system->setCursorPosition(x_new, y_new); /* wrap */
679                         window->setCursorGrabAccum(x_accum + (x_screen - x_new), y_accum + (y_screen - y_new));
680                 }else{
681                         return new GHOST_EventCursor(system->getMilliSeconds(),
682                                                                                  GHOST_kEventCursorMove,
683                                                                                  window,
684                                                                                  x_screen + x_accum,
685                                                                                  y_screen + y_accum
686                         );
687                 }
688
689         }
690         else {
691                 return new GHOST_EventCursor(system->getMilliSeconds(),
692                                                                          GHOST_kEventCursorMove,
693                                                                          window,
694                                                                          x_screen,
695                                                                          y_screen
696                 );
697         }
698         return NULL;
699 }
700
701
702 GHOST_EventWheel* GHOST_SystemWin32::processWheelEvent(GHOST_IWindow *window, WPARAM wParam, LPARAM lParam)
703 {
704         // short fwKeys = LOWORD(wParam);                       // key flags
705         int zDelta = (short) HIWORD(wParam);    // wheel rotation
706         
707         // zDelta /= WHEEL_DELTA;
708         // temporary fix below: microsoft now has added more precision, making the above division not work
709         if (zDelta <= 0 ) zDelta= -1; else zDelta= 1;   
710         
711         // short xPos = (short) LOWORD(lParam); // horizontal position of pointer
712         // short yPos = (short) HIWORD(lParam); // vertical position of pointer
713         return new GHOST_EventWheel (getSystem()->getMilliSeconds(), window, zDelta);
714 }
715
716
717 GHOST_EventKey* GHOST_SystemWin32::processKeyEvent(GHOST_IWindow *window, RAWINPUT const& raw)
718 {
719         int keyDown=0;
720         char vk;
721         GHOST_SystemWin32 * system = (GHOST_SystemWin32 *)getSystem();
722         GHOST_TKey key = system->hardKey(window, raw, &keyDown, &vk);
723         GHOST_EventKey* event;
724
725         if (key != GHOST_kKeyUnknown) {
726                 char utf8_char[6] = {0};
727                 char ascii = 0;
728
729                 wchar_t utf16[3]={0};
730                 BYTE state[256] ={0};
731                 int r;
732                 GetKeyboardState((PBYTE)state);
733
734                 if(r = ToUnicodeEx(vk, 0, state, utf16, 2, 0, system->m_keylayout)) {
735                         if((r>0 && r<3)){
736                                 utf16[r]=0;
737                                 conv_utf_16_to_8(utf16,utf8_char,6);
738                         }
739                         else if (r==-1) {
740                                 utf8_char[0] = '\0';
741                         }
742                 }
743
744                 if(!keyDown) {
745                         utf8_char[0] = '\0';
746                         ascii='\0';
747                 }
748                 else {
749                         ascii = utf8_char[0]& 0x80?'?' : utf8_char[0];
750                 }
751
752                 if(0x80&state[VK_MENU]) utf8_char[0]='\0';
753
754                 event = new GHOST_EventKey(system->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown: GHOST_kEventKeyUp, window, key, ascii, utf8_char);
755                 
756 #ifdef GHOST_DEBUG
757                 std::cout << ascii << std::endl;
758 #endif
759         }
760         else {
761                 event = 0;
762         }
763         return event;
764 }
765
766
767 GHOST_Event* GHOST_SystemWin32::processWindowEvent(GHOST_TEventType type, GHOST_IWindow* window)
768 {
769         GHOST_System* system = (GHOST_System*)getSystem();
770
771         if (type == GHOST_kEventWindowActivate) {
772                 system->getWindowManager()->setActiveWindow(window);
773         }
774
775         return new GHOST_Event(system->getMilliSeconds(), type, window);
776 }
777
778 GHOST_TSuccess GHOST_SystemWin32::pushDragDropEvent(GHOST_TEventType eventType, 
779                                                                                                         GHOST_TDragnDropTypes draggedObjectType,
780                                                                                                         GHOST_IWindow* window,
781                                                                                                         int mouseX, int mouseY,
782                                                                                                         void* data)
783 {
784         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
785         return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
786                                                                                                           eventType,
787                                                                                                           draggedObjectType,
788                                                                                                           window,mouseX,mouseY,data)
789                         );
790 }
791
792 void GHOST_SystemWin32::processMinMaxInfo(MINMAXINFO * minmax)
793 {
794         minmax->ptMinTrackSize.x=320;
795         minmax->ptMinTrackSize.y=240;
796 }
797
798 #ifdef WITH_INPUT_NDOF
799 bool GHOST_SystemWin32::processNDOF(RAWINPUT const& raw)
800 {
801         bool eventSent = false;
802         GHOST_TUns64 now = getMilliSeconds();
803
804         static bool firstEvent = true;
805         if (firstEvent) { // determine exactly which device is plugged in
806                 RID_DEVICE_INFO info;
807                 unsigned infoSize = sizeof(RID_DEVICE_INFO);
808                 info.cbSize = infoSize;
809
810                 GetRawInputDeviceInfo(raw.header.hDevice, RIDI_DEVICEINFO, &info, &infoSize);
811                 if (info.dwType == RIM_TYPEHID)
812                         m_ndofManager->setDevice(info.hid.dwVendorId, info.hid.dwProductId);
813                 else
814                         puts("<!> not a HID device... mouse/kb perhaps?");
815
816                 firstEvent = false;
817         }
818
819         // The NDOF manager sends button changes immediately, and *pretends* to
820         // send motion. Mark as 'sent' so motion will always get dispatched.
821         eventSent = true;
822
823 #if defined(_MSC_VER) || defined(FREE_WINDOWS64)
824         // using Microsoft compiler & header files
825         // they invented the RawInput API, so this version is (probably) correct.
826         // MinGW64 also works fine with this
827         BYTE const* data = raw.data.hid.bRawData;
828         // struct RAWHID {
829         // DWORD dwSizeHid;
830         // DWORD dwCount;
831         // BYTE  bRawData[1];
832         // };
833 #else
834         // MinGW's definition (below) doesn't agree, so we need a slight
835         // workaround until it's fixed
836         BYTE const* data = &raw.data.hid.bRawData;
837         // struct RAWHID {
838         // DWORD dwSizeHid;
839         // DWORD dwCount;
840         // BYTE bRawData; // <== isn't this s'posed to be a BYTE*?
841         // };
842 #endif
843
844         BYTE packetType = data[0];
845         switch (packetType)
846         {
847                 case 1: // translation
848                 {
849                         short* axis = (short*)(data + 1);
850                         // massage into blender view coords (same goes for rotation)
851                         short t[3] = {axis[0], -axis[2], axis[1]};
852                         m_ndofManager->updateTranslation(t, now);
853
854                         if (raw.data.hid.dwSizeHid == 13)
855                         { // this report also includes rotation
856                                 short r[3] = {-axis[3], axis[5], -axis[4]};
857                                 m_ndofManager->updateRotation(r, now);
858
859                                 // I've never gotten one of these, has anyone else?
860                                 puts("ndof: combined T + R");
861                         }
862                         break;
863                 }
864                 case 2: // rotation
865                 {
866                         short* axis = (short*)(data + 1);
867                         short r[3] = {-axis[0], axis[2], -axis[1]};
868                         m_ndofManager->updateRotation(r, now);
869                         break;
870                 }
871                 case 3: // buttons
872                 {
873                         int button_bits;
874                         memcpy(&button_bits, data + 1, sizeof(button_bits));
875                         m_ndofManager->updateButtons(button_bits, now);
876                         break;
877                 }
878         }
879         return eventSent;
880 }
881 #endif // WITH_INPUT_NDOF
882
883 LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
884 {
885         GHOST_Event* event = 0;
886         bool eventHandled = false;
887
888         LRESULT lResult = 0;
889         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
890         GHOST_ASSERT(system, "GHOST_SystemWin32::s_wndProc(): system not initialized")
891
892         if (hwnd) {
893                 GHOST_WindowWin32* window = (GHOST_WindowWin32*)::GetWindowLong(hwnd, GWL_USERDATA);
894                 if (window) {
895                         switch (msg) {
896                                 // we need to check if new key layout has AltGr
897                                 case WM_INPUTLANGCHANGE:
898                                         system->handleKeyboardChange();
899                                         break;
900                                 ////////////////////////////////////////////////////////////////////////
901                                 // Keyboard events, processed
902                                 ////////////////////////////////////////////////////////////////////////
903                                 case WM_INPUT:
904                                 {
905                                         // check WM_INPUT from input sink when ghost window is not in the foreground
906                                         if (wParam == RIM_INPUTSINK) {
907                                                 if (GetFocus() != hwnd) // WM_INPUT message not for this window
908                                                         return 0;
909                                         } //else wParam == RIM_INPUT
910
911                                         RAWINPUT raw;
912                                         RAWINPUT* raw_ptr = &raw;
913                                         UINT rawSize = sizeof(RAWINPUT);
914
915                                         GetRawInputData((HRAWINPUT)lParam, RID_INPUT, raw_ptr, &rawSize, sizeof(RAWINPUTHEADER));
916
917                                         switch (raw.header.dwType)
918                                         {
919                                         case RIM_TYPEKEYBOARD:
920                                                 event = processKeyEvent(window, raw);
921                                                 if (!event) {
922                                                         GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ")
923                                                         GHOST_PRINT(msg)
924                                                         GHOST_PRINT(" key ignored\n")
925                                                 }
926                                                 break;
927 #ifdef WITH_INPUT_NDOF
928                                         case RIM_TYPEHID:
929                                                 if (system->processNDOF(raw))
930                                                         eventHandled = true;
931                                                 break;
932 #endif
933                                         }
934                                 break;
935                                 }
936                                 ////////////////////////////////////////////////////////////////////////
937                                 // Keyboard events, ignored
938                                 ////////////////////////////////////////////////////////////////////////
939                                 case WM_KEYDOWN:
940                                 case WM_SYSKEYDOWN:
941                                 case WM_KEYUP:
942                                 case WM_SYSKEYUP:
943                                         /* These functions were replaced by WM_INPUT*/
944                                 case WM_CHAR:
945                                         /* The WM_CHAR message is posted to the window with the keyboard focus when
946                                          * a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR
947                                          * contains the character code of the key that was pressed.
948                                          */
949                                 case WM_DEADCHAR:
950                                         /* The WM_DEADCHAR message is posted to the window with the keyboard focus when a
951                                          * WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR 
952                                          * specifies a character code generated by a dead key. A dead key is a key that 
953                                          * generates a character, such as the umlaut (double-dot), that is combined with 
954                                          * another character to form a composite character. For example, the umlaut-O 
955                                          * character (Ö) is generated by typing the dead key for the umlaut character, and
956                                          * then typing the O key.
957                                          */
958                                         break;
959                                 case WM_SYSDEADCHAR:
960                                         /* The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when 
961                                          * a WM_SYSKEYDOWN message is translated by the TranslateMessage function. 
962                                          * WM_SYSDEADCHAR specifies the character code of a system dead key - that is, 
963                                          * a dead key that is pressed while holding down the alt key. 
964                                          */
965                                 case WM_SYSCHAR:
966                                         /* The WM_SYSCHAR message is sent to the window with the keyboard focus when 
967                                          * a WM_SYSCHAR message is translated by the TranslateMessage function. 
968                                          * WM_SYSCHAR specifies the character code of a dead key - that is, 
969                                          * a dead key that is pressed while holding down the alt key.
970                                          * To prevent the sound, DefWindowProc must be avoided by return
971                                          */
972                                         break;
973                                 case WM_SYSCOMMAND:
974                                         /* The WM_SYSCHAR message is sent to the window when system commands such as 
975                                          * maximize, minimize  or close the window are triggered. Also it is sent when ALT 
976                                          * button is press for menu. To prevent this we must return preventing DefWindowProc.
977                                          */
978                                         if(wParam==SC_KEYMENU) return 0;
979                                         break;
980                                 ////////////////////////////////////////////////////////////////////////
981                                 // Tablet events, processed
982                                 ////////////////////////////////////////////////////////////////////////
983                                 case WT_PACKET:
984                                         ((GHOST_WindowWin32*)window)->processWin32TabletEvent(wParam, lParam);
985                                         break;
986                                 case WT_CSRCHANGE:
987                                 case WT_PROXIMITY:
988                                         ((GHOST_WindowWin32*)window)->processWin32TabletInitEvent();
989                                         break;
990                                 ////////////////////////////////////////////////////////////////////////
991                                 // Mouse events, processed
992                                 ////////////////////////////////////////////////////////////////////////
993                                 case WM_LBUTTONDOWN:
994                                         window->registerMouseClickEvent(0);
995                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskLeft);
996                                         break;
997                                 case WM_MBUTTONDOWN:
998                                         window->registerMouseClickEvent(0);
999                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskMiddle);
1000                                         break;
1001                                 case WM_RBUTTONDOWN:
1002                                         window->registerMouseClickEvent(0);
1003                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskRight);
1004                                         break;
1005                                 case WM_XBUTTONDOWN:
1006                                         window->registerMouseClickEvent(0);
1007                                         if ((short) HIWORD(wParam) == XBUTTON1){
1008                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton4);
1009                                         }else if((short) HIWORD(wParam) == XBUTTON2){
1010                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton5);
1011                                         }
1012                                         break;
1013                                 case WM_LBUTTONUP:
1014                                         window->registerMouseClickEvent(1);
1015                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskLeft);
1016                                         break;
1017                                 case WM_MBUTTONUP:
1018                                         window->registerMouseClickEvent(1);
1019                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskMiddle);
1020                                         break;
1021                                 case WM_RBUTTONUP:
1022                                         window->registerMouseClickEvent(1);
1023                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskRight);
1024                                         break;
1025                                 case WM_XBUTTONUP:
1026                                         window->registerMouseClickEvent(1);
1027                                         if ((short) HIWORD(wParam) == XBUTTON1){
1028                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton4);
1029                                         }else if((short) HIWORD(wParam) == XBUTTON2){
1030                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton5);
1031                                         }
1032                                         break;
1033                                 case WM_MOUSEMOVE:
1034                                         event = processCursorEvent(GHOST_kEventCursorMove, window);
1035                                         break;
1036                                 case WM_MOUSEWHEEL:
1037                                         /* The WM_MOUSEWHEEL message is sent to the focus window 
1038                                          * when the mouse wheel is rotated. The DefWindowProc 
1039                                          * function propagates the message to the window's parent.
1040                                          * There should be no internal forwarding of the message, 
1041                                          * since DefWindowProc propagates it up the parent chain 
1042                                          * until it finds a window that processes it.
1043                                          */
1044                                         event = processWheelEvent(window, wParam, lParam);
1045                                         break;
1046                                 case WM_SETCURSOR:
1047                                         /* The WM_SETCURSOR message is sent to a window if the mouse causes the cursor
1048                                          * to move within a window and mouse input is not captured.
1049                                          * This means we have to set the cursor shape every time the mouse moves!
1050                                          * The DefWindowProc function uses this message to set the cursor to an 
1051                                          * arrow if it is not in the client area.
1052                                          */
1053                                         if (LOWORD(lParam) == HTCLIENT) {
1054                                                 // Load the current cursor
1055                                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
1056                                                 // Bypass call to DefWindowProc
1057                                                 return 0;
1058                                         } 
1059                                         else {
1060                                                 // Outside of client area show standard cursor
1061                                                 window->loadCursor(true, GHOST_kStandardCursorDefault);
1062                                         }
1063                                         break;
1064
1065                                 ////////////////////////////////////////////////////////////////////////
1066                                 // Mouse events, ignored
1067                                 ////////////////////////////////////////////////////////////////////////
1068                                 case WM_NCMOUSEMOVE:
1069                                         /* The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved 
1070                                          * within the nonclient area of the window. This message is posted to the window 
1071                                          * that contains the cursor. If a window has captured the mouse, this message is not posted.
1072                                          */
1073                                 case WM_NCHITTEST:
1074                                         /* The WM_NCHITTEST message is sent to a window when the cursor moves, or 
1075                                          * when a mouse button is pressed or released. If the mouse is not captured, 
1076                                          * the message is sent to the window beneath the cursor. Otherwise, the message 
1077                                          * is sent to the window that has captured the mouse. 
1078                                          */
1079                                         break;
1080
1081                                 ////////////////////////////////////////////////////////////////////////
1082                                 // Window events, processed
1083                                 ////////////////////////////////////////////////////////////////////////
1084                                 case WM_CLOSE:
1085                                         /* The WM_CLOSE message is sent as a signal that a window or an application should terminate. */
1086                                         event = processWindowEvent(GHOST_kEventWindowClose, window);
1087                                         break;
1088                                 case WM_ACTIVATE:
1089                                         /* The WM_ACTIVATE message is sent to both the window being activated and the window being 
1090                                          * deactivated. If the windows use the same input queue, the message is sent synchronously, 
1091                                          * first to the window procedure of the top-level window being deactivated, then to the window
1092                                          * procedure of the top-level window being activated. If the windows use different input queues,
1093                                          * the message is sent asynchronously, so the window is activated immediately. 
1094                                          */
1095                                         {
1096                                         GHOST_ModifierKeys modifiers;
1097                                         modifiers.clear();
1098                                         system->storeModifierKeys(modifiers);
1099                                         event = processWindowEvent(LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
1100                                         /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
1101                                         will not be dispatched to OUR active window if we minimize one of OUR windows. */
1102                                         lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
1103                                         break;
1104                                         }
1105                                 case WM_PAINT:
1106                                         /* An application sends the WM_PAINT message when the system or another application 
1107                                          * makes a request to paint a portion of an application's window. The message is sent
1108                                          * when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage 
1109                                          * function when the application obtains a WM_PAINT message by using the GetMessage or 
1110                                          * PeekMessage function. 
1111                                          */
1112                                         event = processWindowEvent(GHOST_kEventWindowUpdate, window);
1113                                         ::ValidateRect(hwnd, NULL);
1114                                         break;
1115                                 case WM_GETMINMAXINFO:
1116                                         /* The WM_GETMINMAXINFO message is sent to a window when the size or 
1117                                          * position of the window is about to change. An application can use 
1118                                          * this message to override the window's default maximized size and 
1119                                          * position, or its default minimum or maximum tracking size. 
1120                                          */
1121                                         processMinMaxInfo((MINMAXINFO *) lParam);
1122                                         /* Let DefWindowProc handle it. */
1123                                         break;
1124                                 case WM_SIZE:
1125                                         /* The WM_SIZE message is sent to a window after its size has changed.
1126                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1127                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1128                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1129                                          * message without calling DefWindowProc.
1130                                          */
1131                                         event = processWindowEvent(GHOST_kEventWindowSize, window);
1132                                         break;
1133                                 case WM_CAPTURECHANGED:
1134                                         window->lostMouseCapture();
1135                                         break;
1136                                 case WM_MOVING:
1137                                         /* The WM_MOVING message is sent to a window that the user is moving. By processing 
1138                                          * this message, an application can monitor the size and position of the drag rectangle
1139                                          * and, if needed, change its size or position.
1140                                          */
1141                                 case WM_MOVE:
1142                                         /* The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1143                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1144                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1145                                          * message without calling DefWindowProc. 
1146                                          */
1147                                         event = processWindowEvent(GHOST_kEventWindowMove, window);
1148                                         break;
1149                                 ////////////////////////////////////////////////////////////////////////
1150                                 // Window events, ignored
1151                                 ////////////////////////////////////////////////////////////////////////
1152                                 case WM_WINDOWPOSCHANGED:
1153                                         /* The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place
1154                                          * in the Z order has changed as a result of a call to the SetWindowPos function or 
1155                                          * another window-management function.
1156                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
1157                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
1158                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
1159                                          * message without calling DefWindowProc.
1160                                          */
1161                                 case WM_ERASEBKGND:
1162                                         /* An application sends the WM_ERASEBKGND message when the window background must be 
1163                                          * erased (for example, when a window is resized). The message is sent to prepare an 
1164                                          * invalidated portion of a window for painting. 
1165                                          */
1166                                 case WM_NCPAINT:
1167                                         /* An application sends the WM_NCPAINT message to a window when its frame must be painted. */
1168                                 case WM_NCACTIVATE:
1169                                         /* The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed 
1170                                          * to indicate an active or inactive state. 
1171                                          */
1172                                 case WM_DESTROY:
1173                                         /* The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window 
1174                                          * procedure of the window being destroyed after the window is removed from the screen. 
1175                                          * This message is sent first to the window being destroyed and then to the child windows 
1176                                          * (if any) as they are destroyed. During the processing of the message, it can be assumed 
1177                                          * that all child windows still exist. 
1178                                          */
1179                                 case WM_NCDESTROY:
1180                                         /* The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The 
1181                                          * DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY
1182                                          * message. WM_DESTROY is used to free the allocated memory object associated with the window. 
1183                                          */
1184                                         break;
1185                                 case WM_KILLFOCUS:
1186                                         /* The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus. 
1187                                          * We want to prevent this if a window is still active and it loses focus to nowhere*/
1188                                         if(!wParam && hwnd==GetActiveWindow())
1189                                                 SetFocus(hwnd);
1190                                 case WM_SHOWWINDOW:
1191                                         /* The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown. */
1192                                 case WM_WINDOWPOSCHANGING:
1193                                         /* The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in 
1194                                          * the Z order is about to change as a result of a call to the SetWindowPos function or 
1195                                          * another window-management function. 
1196                                          */
1197                                 case WM_SETFOCUS:
1198                                         /* The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus. */
1199                                 case WM_ENTERSIZEMOVE:
1200                                         /* The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving 
1201                                          * or sizing modal loop. The window enters the moving or sizing modal loop when the user 
1202                                          * clicks the window's title bar or sizing border, or when the window passes the 
1203                                          * WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the 
1204                                          * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when 
1205                                          * DefWindowProc returns. 
1206                                          */
1207                                         break;
1208                                                                         ////////////////////////////////////////////////////////////////////////
1209                                 // Other events
1210                                 ////////////////////////////////////////////////////////////////////////
1211                                 case WM_GETTEXT:
1212                                         /* An application sends a WM_GETTEXT message to copy the text that 
1213                                          * corresponds to a window into a buffer provided by the caller. 
1214                                          */
1215                                 case WM_ACTIVATEAPP:
1216                                         /* The WM_ACTIVATEAPP message is sent when a window belonging to a 
1217                                          * different application than the active window is about to be activated.
1218                                          * The message is sent to the application whose window is being activated
1219                                          * and to the application whose window is being deactivated. 
1220                                          */
1221                                 case WM_TIMER:
1222                                         /* The WIN32 docs say:
1223                                          * The WM_TIMER message is posted to the installing thread's message queue
1224                                          * when a timer expires. You can process the message by providing a WM_TIMER
1225                                          * case in the window procedure. Otherwise, the default window procedure will
1226                                          * call the TimerProc callback function specified in the call to the SetTimer
1227                                          * function used to install the timer. 
1228                                          *
1229                                          * In GHOST, we let DefWindowProc call the timer callback.
1230                                          */
1231                                         break;
1232                         }
1233                 }
1234                 else {
1235                         // Event found for a window before the pointer to the class has been set.
1236                         GHOST_PRINT("GHOST_SystemWin32::wndProc: GHOST window event before creation\n")
1237                         /* These are events we typically miss at this point:
1238                            WM_GETMINMAXINFO     0x24
1239                            WM_NCCREATE                  0x81
1240                            WM_NCCALCSIZE                0x83
1241                            WM_CREATE                    0x01
1242                            We let DefWindowProc do the work.
1243                         */
1244                 }
1245         }
1246         else {
1247                 // Events without valid hwnd
1248                 GHOST_PRINT("GHOST_SystemWin32::wndProc: event without window\n")
1249         }
1250
1251         if (event) {
1252                 system->pushEvent(event);
1253                 eventHandled = true;
1254         }
1255
1256         if (!eventHandled)
1257                 lResult = ::DefWindowProcW(hwnd, msg, wParam, lParam);
1258
1259         return lResult;
1260 }
1261
1262 GHOST_TUns8* GHOST_SystemWin32::getClipboard(bool selection) const 
1263 {
1264         char *temp_buff;
1265         
1266         if ( IsClipboardFormatAvailable(CF_UNICODETEXT) && OpenClipboard(NULL) ) {
1267                 wchar_t *buffer;
1268                 HANDLE hData = GetClipboardData( CF_UNICODETEXT );
1269                 if (hData == NULL) {
1270                         CloseClipboard();
1271                         return NULL;
1272                 }
1273                 buffer = (wchar_t*)GlobalLock( hData );
1274                 if (!buffer) {
1275                         CloseClipboard();
1276                         return NULL;
1277                 }
1278                 
1279                 temp_buff = alloc_utf_8_from_16(buffer,0);
1280                 
1281                 /* Buffer mustn't be accessed after CloseClipboard
1282                    it would like accessing free-d memory */
1283                 GlobalUnlock( hData );
1284                 CloseClipboard();
1285                 
1286                 return (GHOST_TUns8*)temp_buff;
1287         } else if ( IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL) ) {
1288                 char *buffer;
1289                 size_t len = 0;
1290                 HANDLE hData = GetClipboardData( CF_TEXT );
1291                 if (hData == NULL) {
1292                         CloseClipboard();
1293                         return NULL;
1294                 }
1295                 buffer = (char*)GlobalLock( hData );
1296                 if (!buffer) {
1297                         CloseClipboard();
1298                         return NULL;
1299                 }
1300                 
1301                 len = strlen(buffer);
1302                 temp_buff = (char*) malloc(len+1);
1303                 strncpy(temp_buff, buffer, len);
1304                 temp_buff[len] = '\0';
1305                 
1306                 /* Buffer mustn't be accessed after CloseClipboard
1307                    it would like accessing free-d memory */
1308                 GlobalUnlock( hData );
1309                 CloseClipboard();
1310                 
1311                 return (GHOST_TUns8*)temp_buff;
1312         } else {
1313                 return NULL;
1314         }
1315 }
1316
1317 void GHOST_SystemWin32::putClipboard(GHOST_TInt8 *buffer, bool selection) const
1318 {
1319         if(selection) {return;} // for copying the selection, used on X11
1320
1321         if(OpenClipboard(NULL)) {
1322                 HLOCAL clipbuffer;
1323                 wchar_t *data;
1324                 
1325                 if (buffer) {
1326                         size_t len = count_utf_16_from_8(buffer);
1327                         EmptyClipboard();
1328                         
1329                         clipbuffer = LocalAlloc(LMEM_FIXED,sizeof(wchar_t) * len);
1330                         data = (wchar_t*)GlobalLock(clipbuffer);
1331
1332                         conv_utf_8_to_16(buffer, data, len);
1333
1334                         LocalUnlock(clipbuffer);
1335                         SetClipboardData(CF_UNICODETEXT,clipbuffer);
1336                 }
1337                 CloseClipboard();
1338         } else {
1339                 return;
1340         }
1341 }
1342
1343 int GHOST_SystemWin32::toggleConsole(int action)
1344 {
1345         switch(action)
1346         {
1347                 case 3: //hide if no console
1348                         {
1349                                 DWORD sp = GetCurrentProcessId();
1350                                 HANDLE ptree = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
1351                                 PROCESSENTRY32 e = {0}; e.dwSize = sizeof(PROCESSENTRY32);
1352                                 
1353                                 if( Process32First(ptree, &e)) {
1354                                         do { //Searches for Blender's PROCESSENTRY32
1355                                                         if (e.th32ProcessID == sp) {
1356                                                                 sp = e.th32ParentProcessID;
1357                                                                 Process32First(ptree, &e);
1358                                                                         do { //Got parent id, searches for its PROCESSENTRY32
1359                                                                                 if (e.th32ProcessID == sp) {
1360                                                                                         if(strcmp("explorer.exe",e.szExeFile)==0)
1361                                                                                         { //If explorer, hide cmd
1362                                                                                                 ShowWindow(GetConsoleWindow(),SW_HIDE);
1363                                                                                                 m_consoleStatus = 0;
1364                                                                                         }
1365                                                                                         break;
1366                                                                                 }
1367
1368                                                                         } while( Process32Next(ptree, &e));
1369                                                                 break;
1370                                                         }
1371                                         } while( Process32Next(ptree, &e));
1372                                 }
1373
1374                                 CloseHandle(ptree);
1375                                 break;
1376                         }
1377                 case 0: //hide
1378                         ShowWindow(GetConsoleWindow(),SW_HIDE);
1379                         m_consoleStatus = 0;
1380                         break;
1381                 case 1: //show
1382                         ShowWindow(GetConsoleWindow(),SW_SHOW);
1383                         m_consoleStatus = 1;
1384                         break;
1385                 case 2: //toggle
1386                         ShowWindow(GetConsoleWindow(),m_consoleStatus?SW_HIDE:SW_SHOW);
1387                         m_consoleStatus=!m_consoleStatus;
1388                         break;
1389
1390         };
1391
1392
1393         return m_consoleStatus;
1394 }
1395
1396 int GHOST_SystemWin32::confirmQuit(GHOST_IWindow * window) const
1397 {
1398         return (MessageBox(window ? ((GHOST_WindowWin32*)window)->getHWND() : 0, "Some changes have not been saved.\nDo you really want to quit ?",
1399                         "Exit Blender", MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST) == IDOK);
1400 }