soc-2008-mxcurioni: merged changes to revision 23516
[blender.git] / intern / ghost / intern / GHOST_SystemWin32.cpp
1 /**
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /**
30
31  * $Id$
32  * Copyright (C) 2001 NaN Technologies B.V.
33  * @author      Maarten Gribnau
34  * @date        May 7, 2001
35  */
36
37 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 #include "GHOST_SystemWin32.h"
42
43 // win64 doesn't define GWL_USERDATA
44 #ifdef WIN32
45 #ifndef GWL_USERDATA
46 #define GWL_USERDATA GWLP_USERDATA
47 #define GWL_WNDPROC GWLP_WNDPROC
48 #endif
49 #endif
50
51 /*
52  * According to the docs the mouse wheel message is supported from windows 98 
53  * upwards. Leaving WINVER at default value, the WM_MOUSEWHEEL message and the 
54  * wheel detent value are undefined.
55  */
56 #ifndef WM_MOUSEWHEEL
57 #define WM_MOUSEWHEEL 0x020A
58 #endif // WM_MOUSEWHEEL
59 #ifndef WHEEL_DELTA
60 #define WHEEL_DELTA 120 /* Value for rolling one detent, (old convention! MS changed it) */
61 #endif // WHEEL_DELTA
62
63 /* 
64  * Defines for mouse buttons 4 and 5 aka xbutton1 and xbutton2.
65  * MSDN: Declared in Winuser.h, include Windows.h 
66  * This does not seem to work with MinGW so we define our own here.
67  */
68 #ifndef XBUTTON1
69 #define XBUTTON1 0x0001
70 #endif // XBUTTON1
71 #ifndef XBUTTON2
72 #define XBUTTON2 0x0002
73 #endif // XBUTTON2
74 #ifndef WM_XBUTTONUP
75 #define WM_XBUTTONUP 524
76 #endif // WM_XBUTTONUP
77 #ifndef WM_XBUTTONDOWN
78 #define WM_XBUTTONDOWN 523
79 #endif // WM_XBUTTONDOWN
80
81 #include "GHOST_Debug.h"
82 #include "GHOST_DisplayManagerWin32.h"
83 #include "GHOST_EventButton.h"
84 #include "GHOST_EventCursor.h"
85 #include "GHOST_EventKey.h"
86 #include "GHOST_EventWheel.h"
87 #include "GHOST_EventNDOF.h"
88 #include "GHOST_TimerTask.h"
89 #include "GHOST_TimerManager.h"
90 #include "GHOST_WindowManager.h"
91 #include "GHOST_WindowWin32.h"
92 #include "GHOST_NDOFManager.h"
93
94 // Key code values not found in winuser.h
95 #ifndef VK_MINUS
96 #define VK_MINUS 0xBD
97 #endif // VK_MINUS
98 #ifndef VK_SEMICOLON
99 #define VK_SEMICOLON 0xBA
100 #endif // VK_SEMICOLON
101 #ifndef VK_PERIOD
102 #define VK_PERIOD 0xBE
103 #endif // VK_PERIOD
104 #ifndef VK_COMMA
105 #define VK_COMMA 0xBC
106 #endif // VK_COMMA
107 #ifndef VK_QUOTE
108 #define VK_QUOTE 0xDE
109 #endif // VK_QUOTE
110 #ifndef VK_BACK_QUOTE
111 #define VK_BACK_QUOTE 0xC0
112 #endif // VK_BACK_QUOTE
113 #ifndef VK_SLASH
114 #define VK_SLASH 0xBF
115 #endif // VK_SLASH
116 #ifndef VK_BACK_SLASH
117 #define VK_BACK_SLASH 0xDC
118 #endif // VK_BACK_SLASH
119 #ifndef VK_EQUALS
120 #define VK_EQUALS 0xBB
121 #endif // VK_EQUALS
122 #ifndef VK_OPEN_BRACKET
123 #define VK_OPEN_BRACKET 0xDB
124 #endif // VK_OPEN_BRACKET
125 #ifndef VK_CLOSE_BRACKET
126 #define VK_CLOSE_BRACKET 0xDD
127 #endif // VK_CLOSE_BRACKET
128 #ifndef VK_GR_LESS
129 #define VK_GR_LESS 0xE2
130 #endif // VK_GR_LESS
131
132
133 GHOST_SystemWin32::GHOST_SystemWin32()
134 : m_hasPerformanceCounter(false), m_freq(0), m_start(0),
135   m_seperateLeftRight(false),
136   m_seperateLeftRightInitialized(false)
137 {
138         m_displayManager = new GHOST_DisplayManagerWin32 ();
139         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::GHOST_SystemWin32(): m_displayManager==0\n");
140         m_displayManager->initialize();
141 }
142
143 GHOST_SystemWin32::~GHOST_SystemWin32()
144 {
145 }
146
147
148 GHOST_TUns64 GHOST_SystemWin32::getMilliSeconds() const
149 {
150         // Hardware does not support high resolution timers. We will use GetTickCount instead then.
151         if (!m_hasPerformanceCounter) {
152                 return ::GetTickCount();
153         }
154
155         // Retrieve current count
156         __int64 count = 0;
157         ::QueryPerformanceCounter((LARGE_INTEGER*)&count);
158
159         // Calculate the time passed since system initialization.
160         __int64 delta = 1000*(count-m_start);
161
162         GHOST_TUns64 t = (GHOST_TUns64)(delta/m_freq);
163         return t; 
164 }
165
166
167 GHOST_TUns8 GHOST_SystemWin32::getNumDisplays() const
168 {
169         GHOST_ASSERT(m_displayManager, "GHOST_SystemWin32::getNumDisplays(): m_displayManager==0\n");
170         GHOST_TUns8 numDisplays;
171         m_displayManager->getNumDisplays(numDisplays);
172         return numDisplays;
173 }
174
175
176 void GHOST_SystemWin32::getMainDisplayDimensions(GHOST_TUns32& width, GHOST_TUns32& height) const
177 {
178         width = ::GetSystemMetrics(SM_CXSCREEN);
179         height= ::GetSystemMetrics(SM_CYSCREEN);
180 }
181
182
183 GHOST_IWindow* GHOST_SystemWin32::createWindow(
184         const STR_String& title, 
185         GHOST_TInt32 left, GHOST_TInt32 top, GHOST_TUns32 width, GHOST_TUns32 height,
186         GHOST_TWindowState state, GHOST_TDrawingContextType type,
187         bool stereoVisual, const GHOST_TEmbedderWindowID parentWindow )
188 {
189         GHOST_Window* window = 0;
190         window = new GHOST_WindowWin32 (title, left, top, width, height, state, type, stereoVisual);
191         if (window) {
192                 if (window->getValid()) {
193                         // Store the pointer to the window
194 //                      if (state != GHOST_kWindowStateFullScreen) {
195                                 m_windowManager->addWindow(window);
196 //                      }
197                 }
198                 else {
199                         delete window;
200                         window = 0;
201                 }
202         }
203         return window;
204 }
205
206
207 bool GHOST_SystemWin32::processEvents(bool waitForEvent)
208 {
209         MSG msg;
210         bool anyProcessed = false;
211
212         do {
213                 GHOST_TimerManager* timerMgr = getTimerManager();
214
215                 if (waitForEvent && !::PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE)) {
216 #if 1
217                         ::Sleep(1);
218 #else
219                         GHOST_TUns64 next = timerMgr->nextFireTime();
220                         GHOST_TInt64 maxSleep = next - getMilliSeconds();
221                         
222                         if (next == GHOST_kFireTimeNever) {
223                                 ::WaitMessage();
224                         } else if(maxSleep >= 0.0) {
225                                 ::SetTimer(NULL, 0, maxSleep, NULL);
226                                 ::WaitMessage();
227                                 ::KillTimer(NULL, 0);
228                         }
229 #endif
230                 }
231
232                 if (timerMgr->fireTimers(getMilliSeconds())) {
233                         anyProcessed = true;
234                 }
235
236                 // Process all the events waiting for us
237                 while (::PeekMessage(&msg, 0, 0, 0, PM_REMOVE) != 0) {
238                         ::TranslateMessage(&msg);
239                         ::DispatchMessage(&msg);
240                         anyProcessed = true;
241                 }
242         } while (waitForEvent && !anyProcessed);
243
244         return anyProcessed;
245 }
246
247
248 GHOST_TSuccess GHOST_SystemWin32::getCursorPosition(GHOST_TInt32& x, GHOST_TInt32& y) const
249 {
250         POINT point;
251         ::GetCursorPos(&point);
252         x = point.x;
253         y = point.y;
254         return GHOST_kSuccess;
255 }
256
257
258 GHOST_TSuccess GHOST_SystemWin32::setCursorPosition(GHOST_TInt32 x, GHOST_TInt32 y) const
259 {
260         return ::SetCursorPos(x, y) == TRUE ? GHOST_kSuccess : GHOST_kFailure;
261 }
262
263
264 GHOST_TSuccess GHOST_SystemWin32::getModifierKeys(GHOST_ModifierKeys& keys) const
265 {
266         /*
267         GetKeyState and GetAsyncKeyState only work with Win95, Win98, NT4,
268         Terminal Server and Windows 2000.
269         But on WinME it always returns zero. These two functions are simply
270         skipped by Millenium Edition!
271
272         Official explanation from Microsoft:
273         Intentionally disabled.
274         It didn't work all that well on some newer hardware, and worked less 
275         well with the passage of time, so it was fully disabled in ME.
276         */
277         if (m_seperateLeftRight && m_seperateLeftRightInitialized) {
278                 bool down = HIBYTE(::GetKeyState(VK_LSHIFT)) != 0;
279                 keys.set(GHOST_kModifierKeyLeftShift, down);
280                 down = HIBYTE(::GetKeyState(VK_RSHIFT)) != 0;
281                 keys.set(GHOST_kModifierKeyRightShift, down);
282                 down = HIBYTE(::GetKeyState(VK_LMENU)) != 0;
283                 keys.set(GHOST_kModifierKeyLeftAlt, down);
284                 down = HIBYTE(::GetKeyState(VK_RMENU)) != 0;
285                 keys.set(GHOST_kModifierKeyRightAlt, down);
286                 down = HIBYTE(::GetKeyState(VK_LCONTROL)) != 0;
287                 keys.set(GHOST_kModifierKeyLeftControl, down);
288                 down = HIBYTE(::GetKeyState(VK_RCONTROL)) != 0;
289                 keys.set(GHOST_kModifierKeyRightControl, down);
290         }
291         else {
292                 bool down = HIBYTE(::GetKeyState(VK_SHIFT)) != 0;
293                 keys.set(GHOST_kModifierKeyLeftShift, down);
294                 keys.set(GHOST_kModifierKeyRightShift, down);
295                 down = HIBYTE(::GetKeyState(VK_MENU)) != 0;
296                 keys.set(GHOST_kModifierKeyLeftAlt, down);
297                 keys.set(GHOST_kModifierKeyRightAlt, down);
298                 down = HIBYTE(::GetKeyState(VK_CONTROL)) != 0;
299                 keys.set(GHOST_kModifierKeyLeftControl, down);
300                 keys.set(GHOST_kModifierKeyRightControl, down);
301         }
302         return GHOST_kSuccess;
303 }
304
305
306 GHOST_TSuccess GHOST_SystemWin32::getButtons(GHOST_Buttons& buttons) const
307 {
308         /* Check for swapped buttons (left-handed mouse buttons)
309          * GetAsyncKeyState() will give back the state of the physical mouse buttons.
310          */
311         bool swapped = ::GetSystemMetrics(SM_SWAPBUTTON) == TRUE;
312
313         bool down = HIBYTE(::GetKeyState(VK_LBUTTON)) != 0;
314         buttons.set(swapped ? GHOST_kButtonMaskRight : GHOST_kButtonMaskLeft, down);
315
316         down = HIBYTE(::GetKeyState(VK_MBUTTON)) != 0;
317         buttons.set(GHOST_kButtonMaskMiddle, down);
318
319         down = HIBYTE(::GetKeyState(VK_RBUTTON)) != 0;
320         buttons.set(swapped ? GHOST_kButtonMaskLeft : GHOST_kButtonMaskRight, down);
321         return GHOST_kSuccess;
322 }
323
324
325 GHOST_TSuccess GHOST_SystemWin32::init()
326 {
327         GHOST_TSuccess success = GHOST_System::init();
328
329         /* Disable scaling on high DPI displays on Vista */
330         HMODULE user32 = ::LoadLibraryA("user32.dll");
331         typedef BOOL (WINAPI * LPFNSETPROCESSDPIAWARE)();
332         LPFNSETPROCESSDPIAWARE SetProcessDPIAware =
333                 (LPFNSETPROCESSDPIAWARE)GetProcAddress(user32, "SetProcessDPIAware");
334         if (SetProcessDPIAware)
335                 SetProcessDPIAware();
336         FreeLibrary(user32);
337
338         // Determine whether this system has a high frequency performance counter. */
339         m_hasPerformanceCounter = ::QueryPerformanceFrequency((LARGE_INTEGER*)&m_freq) == TRUE;
340         if (m_hasPerformanceCounter) {
341                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer available\n")
342                 ::QueryPerformanceCounter((LARGE_INTEGER*)&m_start);
343         }
344         else {
345                 GHOST_PRINT("GHOST_SystemWin32::init: High Frequency Performance Timer not available\n")
346         }
347
348         if (success) {
349                 WNDCLASS wc;
350                 wc.style= CS_HREDRAW | CS_VREDRAW;
351                 wc.lpfnWndProc= s_wndProc;
352                 wc.cbClsExtra= 0;
353                 wc.cbWndExtra= 0;
354                 wc.hInstance= ::GetModuleHandle(0);
355                 wc.hIcon = ::LoadIcon(wc.hInstance, "APPICON");
356                 
357                 if (!wc.hIcon) {
358                         ::LoadIcon(NULL, IDI_APPLICATION);
359                 }
360                 wc.hCursor = ::LoadCursor(0, IDC_ARROW);
361                 wc.hbrBackground= (HBRUSH)::GetStockObject(BLACK_BRUSH);
362                 wc.lpszMenuName = 0;
363                 wc.lpszClassName= GHOST_WindowWin32::getWindowClassName();
364     
365                 // Use RegisterClassEx for setting small icon
366                 if (::RegisterClass(&wc) == 0) {
367                         success = GHOST_kFailure;
368                 }
369         }
370         return success;
371 }
372
373
374 GHOST_TSuccess GHOST_SystemWin32::exit()
375 {
376         return GHOST_System::exit();
377 }
378
379
380 GHOST_TKey GHOST_SystemWin32::convertKey(WPARAM wParam, LPARAM lParam) const
381 {
382         GHOST_TKey key;
383         bool isExtended = (lParam&(1<<24))?true:false;
384
385         if ((wParam >= '0') && (wParam <= '9')) {
386                 // VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39)
387                 key = (GHOST_TKey)(wParam - '0' + GHOST_kKey0);
388         }
389         else if ((wParam >= 'A') && (wParam <= 'Z')) {
390                 // VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A)
391                 key = (GHOST_TKey)(wParam - 'A' + GHOST_kKeyA);
392         }
393         else if ((wParam >= VK_F1) && (wParam <= VK_F24)) {
394                 key = (GHOST_TKey)(wParam - VK_F1 + GHOST_kKeyF1);
395         }
396         else {
397                 switch (wParam) {
398                 case VK_RETURN:
399                         key = isExtended?GHOST_kKeyNumpadEnter:GHOST_kKeyEnter;
400                         break;
401
402                 case VK_BACK:     key = GHOST_kKeyBackSpace;            break;
403                 case VK_TAB:      key = GHOST_kKeyTab;                          break;
404                 case VK_ESCAPE:   key = GHOST_kKeyEsc;                          break;
405                 case VK_SPACE:    key = GHOST_kKeySpace;                        break;
406                 case VK_PRIOR:    key = GHOST_kKeyUpPage;                       break;
407                 case VK_NEXT:     key = GHOST_kKeyDownPage;                     break;
408                 case VK_END:      key = GHOST_kKeyEnd;                          break;
409                 case VK_HOME:     key = GHOST_kKeyHome;                         break;
410                 case VK_INSERT:   key = GHOST_kKeyInsert;                       break;
411                 case VK_DELETE:   key = GHOST_kKeyDelete;                       break;
412                 case VK_LEFT:     key = GHOST_kKeyLeftArrow;            break;
413                 case VK_RIGHT:    key = GHOST_kKeyRightArrow;           break;
414                 case VK_UP:       key = GHOST_kKeyUpArrow;                      break;
415                 case VK_DOWN:     key = GHOST_kKeyDownArrow;            break;
416                 case VK_NUMPAD0:  key = GHOST_kKeyNumpad0;                      break;
417                 case VK_NUMPAD1:  key = GHOST_kKeyNumpad1;                      break;
418                 case VK_NUMPAD2:  key = GHOST_kKeyNumpad2;                      break;
419                 case VK_NUMPAD3:  key = GHOST_kKeyNumpad3;                      break;
420                 case VK_NUMPAD4:  key = GHOST_kKeyNumpad4;                      break;
421                 case VK_NUMPAD5:  key = GHOST_kKeyNumpad5;                      break;
422                 case VK_NUMPAD6:  key = GHOST_kKeyNumpad6;                      break;
423                 case VK_NUMPAD7:  key = GHOST_kKeyNumpad7;                      break;
424                 case VK_NUMPAD8:  key = GHOST_kKeyNumpad8;                      break;
425                 case VK_NUMPAD9:  key = GHOST_kKeyNumpad9;                      break;
426                 case VK_SNAPSHOT: key = GHOST_kKeyPrintScreen;          break;
427                 case VK_PAUSE:    key = GHOST_kKeyPause;                        break;
428                 case VK_MULTIPLY: key = GHOST_kKeyNumpadAsterisk;        break;
429                 case VK_SUBTRACT: key = GHOST_kKeyNumpadMinus;          break;
430                 case VK_DECIMAL:  key = GHOST_kKeyNumpadPeriod;         break;
431                 case VK_DIVIDE:   key = GHOST_kKeyNumpadSlash;          break;
432                 case VK_ADD:      key = GHOST_kKeyNumpadPlus;           break;
433
434                 case VK_SEMICOLON:              key = GHOST_kKeySemicolon;              break;
435                 case VK_EQUALS:                 key = GHOST_kKeyEqual;                  break;
436                 case VK_COMMA:                  key = GHOST_kKeyComma;                  break;
437                 case VK_MINUS:                  key = GHOST_kKeyMinus;                  break;
438                 case VK_PERIOD:                 key = GHOST_kKeyPeriod;                 break;
439                 case VK_SLASH:                  key = GHOST_kKeySlash;                  break;
440                 case VK_BACK_QUOTE:             key = GHOST_kKeyAccentGrave;    break;
441                 case VK_OPEN_BRACKET:   key = GHOST_kKeyLeftBracket;    break;
442                 case VK_BACK_SLASH:             key = GHOST_kKeyBackslash;              break;
443                 case VK_CLOSE_BRACKET:  key = GHOST_kKeyRightBracket;   break;
444                 case VK_QUOTE:                  key = GHOST_kKeyQuote;                  break;
445                 case VK_GR_LESS:                key = GHOST_kKeyGrLess;                 break;
446
447                 // Process these keys separately because we need to distinguish right from left modifier keys
448                 case VK_SHIFT:
449                 case VK_CONTROL:
450                 case VK_MENU:
451
452                 // Ignore these keys
453                 case VK_NUMLOCK:
454                 case VK_SCROLL:
455                 case VK_CAPITAL:
456                 default:
457                         key = GHOST_kKeyUnknown;
458                         break;
459                 }
460         }
461         return key;
462 }
463
464
465 void GHOST_SystemWin32::processModifierKeys(GHOST_IWindow *window)
466 {
467         GHOST_ModifierKeys oldModifiers, newModifiers;
468         // Retrieve old state of the modifier keys
469         ((GHOST_SystemWin32*)getSystem())->retrieveModifierKeys(oldModifiers);
470         // Retrieve current state of the modifier keys
471         ((GHOST_SystemWin32*)getSystem())->getModifierKeys(newModifiers);
472
473         // Compare the old and the new
474         if (!newModifiers.equals(oldModifiers)) {
475                 // Create events for the masks that changed
476                 for (int i = 0; i < GHOST_kModifierKeyNumMasks; i++) {
477                         if (newModifiers.get((GHOST_TModifierKeyMask)i) != oldModifiers.get((GHOST_TModifierKeyMask)i)) {
478                                 // Convert the mask to a key code
479                                 GHOST_TKey key = GHOST_ModifierKeys::getModifierKeyCode((GHOST_TModifierKeyMask)i);
480                                 bool keyDown = newModifiers.get((GHOST_TModifierKeyMask)i);
481                                 GHOST_EventKey* event;
482                                 if (key != GHOST_kKeyUnknown) {
483                                         // Create an event
484                                         event = new GHOST_EventKey(getSystem()->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown: GHOST_kEventKeyUp, window, key);
485                                         pushEvent(event);
486                                 }
487                         }
488                 }
489         }
490
491         // Store new modifier keys state
492         ((GHOST_SystemWin32*)getSystem())->storeModifierKeys(newModifiers);
493 }
494
495
496 GHOST_EventButton* GHOST_SystemWin32::processButtonEvent(GHOST_TEventType type, GHOST_IWindow *window, GHOST_TButtonMask mask)
497 {
498         return new GHOST_EventButton (getSystem()->getMilliSeconds(), type, window, mask);
499 }
500
501
502 GHOST_EventCursor* GHOST_SystemWin32::processCursorEvent(GHOST_TEventType type, GHOST_IWindow *window)
503 {
504         GHOST_TInt32 x, y;
505         getSystem()->getCursorPosition(x, y);
506         return new GHOST_EventCursor (getSystem()->getMilliSeconds(), type, window, x, y);
507 }
508
509
510 GHOST_EventWheel* GHOST_SystemWin32::processWheelEvent(GHOST_IWindow *window, WPARAM wParam, LPARAM lParam)
511 {
512         // short fwKeys = LOWORD(wParam);                       // key flags
513         int zDelta = (short) HIWORD(wParam);    // wheel rotation
514         
515         // zDelta /= WHEEL_DELTA;
516         // temporary fix below: microsoft now has added more precision, making the above division not work
517         if (zDelta <= 0 ) zDelta= -1; else zDelta= 1;   
518         
519         // short xPos = (short) LOWORD(lParam); // horizontal position of pointer
520         // short yPos = (short) HIWORD(lParam); // vertical position of pointer
521         return new GHOST_EventWheel (getSystem()->getMilliSeconds(), window, zDelta);
522 }
523
524
525 GHOST_EventKey* GHOST_SystemWin32::processKeyEvent(GHOST_IWindow *window, bool keyDown, WPARAM wParam, LPARAM lParam)
526 {
527         GHOST_TKey key = ((GHOST_SystemWin32*)getSystem())->convertKey(wParam, lParam);
528         GHOST_EventKey* event;
529         if (key != GHOST_kKeyUnknown) {
530                 MSG keyMsg;
531                 char ascii = '\0';
532
533                         /* Eat any character related messages */
534                 if (::PeekMessage(&keyMsg, NULL, WM_CHAR, WM_SYSDEADCHAR, PM_REMOVE)) {
535                         ascii = (char) keyMsg.wParam;
536                 }
537
538                 event = new GHOST_EventKey(getSystem()->getMilliSeconds(), keyDown ? GHOST_kEventKeyDown: GHOST_kEventKeyUp, window, key, ascii);
539         }
540         else {
541                 event = 0;
542         }
543         return event;
544 }
545
546
547 GHOST_Event* GHOST_SystemWin32::processWindowEvent(GHOST_TEventType type, GHOST_IWindow* window)
548 {
549         return new GHOST_Event(getSystem()->getMilliSeconds(), type, window);
550 }
551
552
553 LRESULT WINAPI GHOST_SystemWin32::s_wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
554 {
555         GHOST_Event* event = 0;
556         LRESULT lResult = 0;
557         GHOST_SystemWin32* system = ((GHOST_SystemWin32*)getSystem());
558         GHOST_ASSERT(system, "GHOST_SystemWin32::s_wndProc(): system not initialized")
559
560         if (hwnd) {
561                 GHOST_WindowWin32* window = (GHOST_WindowWin32*)::GetWindowLong(hwnd, GWL_USERDATA);
562                 if (window) {
563                         switch (msg) {
564                                 ////////////////////////////////////////////////////////////////////////
565                                 // Keyboard events, processed
566                                 ////////////////////////////////////////////////////////////////////////
567                                 case WM_KEYDOWN:
568                                         /* The WM_KEYDOWN message is posted to the window with the keyboard focus when a 
569                                          * nonsystem key is pressed. A nonsystem key is a key that is pressed when the alt
570                                          * key is not pressed. 
571                                          */
572                                 case WM_SYSKEYDOWN:
573                                         /* The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when 
574                                          * the user presses the F10 key (which activates the menu bar) or holds down the 
575                                          * alt key and then presses another key. It also occurs when no window currently 
576                                          * has the keyboard focus; in this case, the WM_SYSKEYDOWN message is sent to the 
577                                          * active window. The window that receives the message can distinguish between these 
578                                          * two contexts by checking the context code in the lKeyData parameter. 
579                                          */
580                                         switch (wParam) {
581                                                 case VK_SHIFT:
582                                                 case VK_CONTROL:
583                                                 case VK_MENU:
584                                                         if (!system->m_seperateLeftRightInitialized) {
585                                                                 // Check whether this system supports seperate left and right keys
586                                                                 switch (wParam) {
587                                                                         case VK_SHIFT:
588                                                                                 system->m_seperateLeftRight = 
589                                                                                         (HIBYTE(::GetKeyState(VK_LSHIFT)) != 0) ||
590                                                                                         (HIBYTE(::GetKeyState(VK_RSHIFT)) != 0) ?
591                                                                                         true : false;
592                                                                                 break;
593                                                                         case VK_CONTROL:
594                                                                                 system->m_seperateLeftRight = 
595                                                                                         (HIBYTE(::GetKeyState(VK_LCONTROL)) != 0) ||
596                                                                                         (HIBYTE(::GetKeyState(VK_RCONTROL)) != 0) ?
597                                                                                         true : false;
598                                                                                 break;
599                                                                         case VK_MENU:
600                                                                                 system->m_seperateLeftRight = 
601                                                                                         (HIBYTE(::GetKeyState(VK_LMENU)) != 0) ||
602                                                                                         (HIBYTE(::GetKeyState(VK_RMENU)) != 0) ?
603                                                                                         true : false;
604                                                                                 break;
605                                                                 }
606                                                                 system->m_seperateLeftRightInitialized = true;
607                                                         }
608                                                         system->processModifierKeys(window);
609                                                         // Bypass call to DefWindowProc
610                                                         return 0;
611                                                 default:
612                                                         event = processKeyEvent(window, true, wParam, lParam);
613                                                         if (!event) {
614                                                                 GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ")
615                                                                 GHOST_PRINT(msg)
616                                                                 GHOST_PRINT(" key ignored\n")
617                                                         }
618                                                         break;
619                                                 }
620                                         break;
621
622                                 case WM_KEYUP:
623                                 case WM_SYSKEYUP:
624                                         switch (wParam) {
625                                                 case VK_SHIFT:
626                                                 case VK_CONTROL:
627                                                 case VK_MENU:
628                                                         system->processModifierKeys(window);
629                                                         // Bypass call to DefWindowProc
630                                                         return 0;
631                                                 default:
632                                                         event = processKeyEvent(window, false, wParam, lParam);
633                                                         if (!event) {
634                                                                 GHOST_PRINT("GHOST_SystemWin32::wndProc: key event ")
635                                                                 GHOST_PRINT(msg)
636                                                                 GHOST_PRINT(" key ignored\n")
637                                                         }
638                                                         break;
639                                         }
640                                         break;
641
642                                 ////////////////////////////////////////////////////////////////////////
643                                 // Keyboard events, ignored
644                                 ////////////////////////////////////////////////////////////////////////
645                                 case WM_CHAR:
646                                         /* The WM_CHAR message is posted to the window with the keyboard focus when 
647                                          * a WM_KEYDOWN message is translated by the TranslateMessage function. WM_CHAR 
648                                          * contains the character code of the key that was pressed. 
649                                          */
650                                 case WM_DEADCHAR:
651                                         /* The WM_DEADCHAR message is posted to the window with the keyboard focus when a
652                                          * WM_KEYUP message is translated by the TranslateMessage function. WM_DEADCHAR 
653                                          * specifies a character code generated by a dead key. A dead key is a key that 
654                                          * generates a character, such as the umlaut (double-dot), that is combined with 
655                                          * another character to form a composite character. For example, the umlaut-O 
656                                          * character (Ù) is generated by typing the dead key for the umlaut character, and 
657                                          * then typing the O key.
658                                          */
659                                 case WM_SYSDEADCHAR:
660                                         /* The WM_SYSDEADCHAR message is sent to the window with the keyboard focus when 
661                                          * a WM_SYSKEYDOWN message is translated by the TranslateMessage function. 
662                                          * WM_SYSDEADCHAR specifies the character code of a system dead key - that is, 
663                                          * a dead key that is pressed while holding down the alt key. 
664                                          */
665                                         break;
666                                 ////////////////////////////////////////////////////////////////////////
667                                 // Tablet events, processed
668                                 ////////////////////////////////////////////////////////////////////////
669                                 case WT_PACKET:
670                                         ((GHOST_WindowWin32*)window)->processWin32TabletEvent(wParam, lParam);
671                                         break;
672                                 case WT_CSRCHANGE:
673                                 case WT_PROXIMITY:
674                                         ((GHOST_WindowWin32*)window)->processWin32TabletInitEvent();
675                                         break;
676                                 ////////////////////////////////////////////////////////////////////////
677                                 // Mouse events, processed
678                                 ////////////////////////////////////////////////////////////////////////
679                                 case WM_LBUTTONDOWN:
680                                         window->registerMouseClickEvent(true);
681                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskLeft);
682                                         break;
683                                 case WM_MBUTTONDOWN:
684                                         window->registerMouseClickEvent(true);
685                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskMiddle);
686                                         break;
687                                 case WM_RBUTTONDOWN:
688                                         window->registerMouseClickEvent(true);
689                                         event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskRight);
690                                         break;
691                                 case WM_XBUTTONDOWN:
692                                         window->registerMouseClickEvent(true);
693                                         if ((short) HIWORD(wParam) == XBUTTON1){
694                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton4);
695                                         }else if((short) HIWORD(wParam) == XBUTTON2){
696                                                 event = processButtonEvent(GHOST_kEventButtonDown, window, GHOST_kButtonMaskButton5);
697                                         }
698                                         break;
699                                 case WM_LBUTTONUP:
700                                         window->registerMouseClickEvent(false);
701                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskLeft);
702                                         break;
703                                 case WM_MBUTTONUP:
704                                         window->registerMouseClickEvent(false);
705                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskMiddle);
706                                         break;
707                                 case WM_RBUTTONUP:
708                                         window->registerMouseClickEvent(false);
709                                         event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskRight);
710                                         break;
711                                 case WM_XBUTTONUP:
712                                         window->registerMouseClickEvent(false);
713                                         if ((short) HIWORD(wParam) == XBUTTON1){
714                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton4);
715                                         }else if((short) HIWORD(wParam) == XBUTTON2){
716                                                 event = processButtonEvent(GHOST_kEventButtonUp, window, GHOST_kButtonMaskButton5);
717                                         }
718                                         break;
719                                 case WM_MOUSEMOVE:
720                                         event = processCursorEvent(GHOST_kEventCursorMove, window);
721                                         break;
722                                 case WM_MOUSEWHEEL:
723                                         /* The WM_MOUSEWHEEL message is sent to the focus window 
724                                          * when the mouse wheel is rotated. The DefWindowProc 
725                                          * function propagates the message to the window's parent.
726                                          * There should be no internal forwarding of the message, 
727                                          * since DefWindowProc propagates it up the parent chain 
728                                          * until it finds a window that processes it.
729                                          */
730                                         event = processWheelEvent(window, wParam, lParam);
731                                         break;
732                                 case WM_SETCURSOR:
733                                         /* The WM_SETCURSOR message is sent to a window if the mouse causes the cursor
734                                          * to move within a window and mouse input is not captured.
735                                          * This means we have to set the cursor shape every time the mouse moves!
736                                          * The DefWindowProc function uses this message to set the cursor to an 
737                                          * arrow if it is not in the client area.
738                                          */
739                                         if (LOWORD(lParam) == HTCLIENT) {
740                                                 // Load the current cursor
741                                                 window->loadCursor(window->getCursorVisibility(), window->getCursorShape());
742                                                 // Bypass call to DefWindowProc
743                                                 return 0;
744                                         } 
745                                         else {
746                                                 // Outside of client area show standard cursor
747                                                 window->loadCursor(true, GHOST_kStandardCursorDefault);
748                                         }
749                                         break;
750
751                                 ////////////////////////////////////////////////////////////////////////
752                                 // Mouse events, ignored
753                                 ////////////////////////////////////////////////////////////////////////
754                                 case WM_NCMOUSEMOVE:
755                                         /* The WM_NCMOUSEMOVE message is posted to a window when the cursor is moved 
756                                          * within the nonclient area of the window. This message is posted to the window 
757                                          * that contains the cursor. If a window has captured the mouse, this message is not posted.
758                                          */
759                                 case WM_NCHITTEST:
760                                         /* The WM_NCHITTEST message is sent to a window when the cursor moves, or 
761                                          * when a mouse button is pressed or released. If the mouse is not captured, 
762                                          * the message is sent to the window beneath the cursor. Otherwise, the message 
763                                          * is sent to the window that has captured the mouse. 
764                                          */
765                                         break;
766
767                                 ////////////////////////////////////////////////////////////////////////
768                                 // Window events, processed
769                                 ////////////////////////////////////////////////////////////////////////
770                                 case WM_CLOSE:
771                                         /* The WM_CLOSE message is sent as a signal that a window or an application should terminate. */
772                                         event = processWindowEvent(GHOST_kEventWindowClose, window);
773                                         break;
774                                 case WM_ACTIVATE:
775                                         /* The WM_ACTIVATE message is sent to both the window being activated and the window being 
776                                          * deactivated. If the windows use the same input queue, the message is sent synchronously, 
777                                          * first to the window procedure of the top-level window being deactivated, then to the window
778                                          * procedure of the top-level window being activated. If the windows use different input queues,
779                                          * the message is sent asynchronously, so the window is activated immediately. 
780                                          */
781                                         event = processWindowEvent(LOWORD(wParam) ? GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate, window);
782                                         /* WARNING: Let DefWindowProc handle WM_ACTIVATE, otherwise WM_MOUSEWHEEL
783                                         will not be dispatched to OUR active window if we minimize one of OUR windows. */
784                                         lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
785                                         break;
786                                 case WM_PAINT:
787                                         /* An application sends the WM_PAINT message when the system or another application 
788                                          * makes a request to paint a portion of an application's window. The message is sent
789                                          * when the UpdateWindow or RedrawWindow function is called, or by the DispatchMessage 
790                                          * function when the application obtains a WM_PAINT message by using the GetMessage or 
791                                          * PeekMessage function. 
792                                          */
793                                         event = processWindowEvent(GHOST_kEventWindowUpdate, window);
794                                         ::ValidateRect(hwnd, NULL);
795                                         break;
796                                 case WM_SIZE:
797                                         /* The WM_SIZE message is sent to a window after its size has changed.
798                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
799                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
800                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
801                                          * message without calling DefWindowProc.
802                                          */
803                                         event = processWindowEvent(GHOST_kEventWindowSize, window);
804                                         break;
805                                 case WM_CAPTURECHANGED:
806                                         window->lostMouseCapture();
807                                         break;
808                                 case WM_MOVING:
809                                         /* The WM_MOVING message is sent to a window that the user is moving. By processing 
810                                          * this message, an application can monitor the size and position of the drag rectangle
811                                          * and, if needed, change its size or position.
812                                          */
813                                 case WM_MOVE:
814                                         /* The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
815                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
816                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
817                                          * message without calling DefWindowProc. 
818                                          */
819                                         event = processWindowEvent(GHOST_kEventWindowMove, window);
820                                         break;
821                                 ////////////////////////////////////////////////////////////////////////
822                                 // Window events, ignored
823                                 ////////////////////////////////////////////////////////////////////////
824                                 case WM_WINDOWPOSCHANGED:
825                                         /* The WM_WINDOWPOSCHANGED message is sent to a window whose size, position, or place
826                                          * in the Z order has changed as a result of a call to the SetWindowPos function or 
827                                          * another window-management function.
828                                          * The WM_SIZE and WM_MOVE messages are not sent if an application handles the 
829                                          * WM_WINDOWPOSCHANGED message without calling DefWindowProc. It is more efficient
830                                          * to perform any move or size change processing during the WM_WINDOWPOSCHANGED 
831                                          * message without calling DefWindowProc.
832                                          */
833                                 case WM_ERASEBKGND:
834                                         /* An application sends the WM_ERASEBKGND message when the window background must be 
835                                          * erased (for example, when a window is resized). The message is sent to prepare an 
836                                          * invalidated portion of a window for painting. 
837                                          */
838                                 case WM_NCPAINT:
839                                         /* An application sends the WM_NCPAINT message to a window when its frame must be painted. */
840                                 case WM_NCACTIVATE:
841                                         /* The WM_NCACTIVATE message is sent to a window when its nonclient area needs to be changed 
842                                          * to indicate an active or inactive state. 
843                                          */
844                                 case WM_DESTROY:
845                                         /* The WM_DESTROY message is sent when a window is being destroyed. It is sent to the window 
846                                          * procedure of the window being destroyed after the window is removed from the screen. 
847                                          * This message is sent first to the window being destroyed and then to the child windows 
848                                          * (if any) as they are destroyed. During the processing of the message, it can be assumed 
849                                          * that all child windows still exist. 
850                                          */
851                                 case WM_NCDESTROY:
852                                         /* The WM_NCDESTROY message informs a window that its nonclient area is being destroyed. The 
853                                          * DestroyWindow function sends the WM_NCDESTROY message to the window following the WM_DESTROY
854                                          * message. WM_DESTROY is used to free the allocated memory object associated with the window. 
855                                          */
856                                 case WM_KILLFOCUS:
857                                         /* The WM_KILLFOCUS message is sent to a window immediately before it loses the keyboard focus. */
858                                 case WM_SHOWWINDOW:
859                                         /* The WM_SHOWWINDOW message is sent to a window when the window is about to be hidden or shown. */
860                                 case WM_WINDOWPOSCHANGING:
861                                         /* The WM_WINDOWPOSCHANGING message is sent to a window whose size, position, or place in 
862                                          * the Z order is about to change as a result of a call to the SetWindowPos function or 
863                                          * another window-management function. 
864                                          */
865                                 case WM_SETFOCUS:
866                                         /* The WM_SETFOCUS message is sent to a window after it has gained the keyboard focus. */
867                                 case WM_ENTERSIZEMOVE:
868                                         /* The WM_ENTERSIZEMOVE message is sent one time to a window after it enters the moving 
869                                          * or sizing modal loop. The window enters the moving or sizing modal loop when the user 
870                                          * clicks the window's title bar or sizing border, or when the window passes the 
871                                          * WM_SYSCOMMAND message to the DefWindowProc function and the wParam parameter of the 
872                                          * message specifies the SC_MOVE or SC_SIZE value. The operation is complete when 
873                                          * DefWindowProc returns. 
874                                          */
875                                         break;
876                                         
877                                 ////////////////////////////////////////////////////////////////////////
878                                 // Other events
879                                 ////////////////////////////////////////////////////////////////////////
880                                 case WM_GETTEXT:
881                                         /* An application sends a WM_GETTEXT message to copy the text that 
882                                          * corresponds to a window into a buffer provided by the caller. 
883                                          */
884                                 case WM_ACTIVATEAPP:
885                                         /* The WM_ACTIVATEAPP message is sent when a window belonging to a 
886                                          * different application than the active window is about to be activated.
887                                          * The message is sent to the application whose window is being activated
888                                          * and to the application whose window is being deactivated. 
889                                          */
890                                 case WM_TIMER:
891                                         /* The WIN32 docs say:
892                                          * The WM_TIMER message is posted to the installing thread's message queue
893                                          * when a timer expires. You can process the message by providing a WM_TIMER
894                                          * case in the window procedure. Otherwise, the default window procedure will
895                                          * call the TimerProc callback function specified in the call to the SetTimer
896                                          * function used to install the timer. 
897                                          *
898                                          * In GHOST, we let DefWindowProc call the timer callback.
899                                          */
900                                         break;
901                                 case WM_BLND_NDOF_AXIS:
902                                         {
903                                                 GHOST_TEventNDOFData ndofdata;
904                                                 system->m_ndofManager->GHOST_NDOFGetDatas(ndofdata);
905                                                 system->m_eventManager->
906                                                         pushEvent(new GHOST_EventNDOF(
907                                                                 system->getMilliSeconds(), 
908                                                                 GHOST_kEventNDOFMotion, 
909                                                                 window, ndofdata));
910                                         }
911                                         break;
912                                 case WM_BLND_NDOF_BTN:
913                                         {
914                                                 GHOST_TEventNDOFData ndofdata;
915                                                 system->m_ndofManager->GHOST_NDOFGetDatas(ndofdata);
916                                                 system->m_eventManager->
917                                                         pushEvent(new GHOST_EventNDOF(
918                                                                 system->getMilliSeconds(), 
919                                                                 GHOST_kEventNDOFButton, 
920                                                                 window, ndofdata));
921                                         }
922                                         break;
923                         }
924                 }
925                 else {
926                         // Event found for a window before the pointer to the class has been set.
927                         GHOST_PRINT("GHOST_SystemWin32::wndProc: GHOST window event before creation\n")
928                         /* These are events we typically miss at this point:
929                            WM_GETMINMAXINFO     0x24
930                            WM_NCCREATE                  0x81
931                            WM_NCCALCSIZE                0x83
932                            WM_CREATE                    0x01
933                            We let DefWindowProc do the work.
934                         */
935                 }
936         }
937         else {
938                 // Events without valid hwnd
939                 GHOST_PRINT("GHOST_SystemWin32::wndProc: event without window\n")
940         }
941
942         if (event) {
943                 system->pushEvent(event);
944         }
945         else {
946                 lResult = ::DefWindowProc(hwnd, msg, wParam, lParam);
947         }
948         return lResult;
949 }
950
951 GHOST_TUns8* GHOST_SystemWin32::getClipboard(bool selection) const 
952 {
953         char *buffer;
954         char *temp_buff;
955         
956         if ( IsClipboardFormatAvailable(CF_TEXT) && OpenClipboard(NULL) ) {
957                 HANDLE hData = GetClipboardData( CF_TEXT );
958                 if (hData == NULL) {
959                         CloseClipboard();
960                         return NULL;
961                 }
962                 buffer = (char*)GlobalLock( hData );
963                 
964                 temp_buff = (char*) malloc(strlen(buffer)+1);
965                 strcpy(temp_buff, buffer);
966                 
967                 GlobalUnlock( hData );
968                 CloseClipboard();
969                 
970                 temp_buff[strlen(buffer)] = '\0';
971                 if (buffer) {
972                         return (GHOST_TUns8*)temp_buff;
973                 } else {
974                         return NULL;
975                 }
976         } else {
977                 return NULL;
978         }
979 }
980
981 void GHOST_SystemWin32::putClipboard(GHOST_TInt8 *buffer, bool selection) const
982 {
983         if(selection) {return;} // for copying the selection, used on X11
984
985         if (OpenClipboard(NULL)) {
986                 HLOCAL clipbuffer;
987                 char *data;
988                 
989                 if (buffer) {
990                         EmptyClipboard();
991                         
992                         clipbuffer = LocalAlloc(LMEM_FIXED,((strlen(buffer)+1)));
993                         data = (char*)GlobalLock(clipbuffer);
994
995                         strcpy(data, (char*)buffer);
996                         data[strlen(buffer)] = '\0';
997                         LocalUnlock(clipbuffer);
998                         SetClipboardData(CF_TEXT,clipbuffer);
999                 }
1000                 CloseClipboard();
1001         } else {
1002                 return;
1003         }
1004 }
1005