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