winDispatch.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #define NO_MINMAX
  23. #define WIN32_LEAN_AND_MEAN
  24. // This is a fix for mouse wheel support on
  25. // older versions of VC++.
  26. #if _MSC_VER < 1500
  27. #define _WIN32_WINNT 0x0400
  28. #endif
  29. #include <windows.h>
  30. #include "platform/platformInput.h"
  31. #include "windowManager/win32/winDispatch.h"
  32. #include "windowManager/win32/win32Window.h"
  33. #include "windowManager/win32/win32CursorController.h"
  34. #include "platformWin32/winDirectInput.h"
  35. #include "core/util/journal/process.h"
  36. #include "core/util/journal/journaledSignal.h"
  37. static U32 _ModifierKeys=0;
  38. static BYTE keyboardState[256];
  39. static bool initKBState = false;
  40. static bool sgDoubleByteEnabled = false;
  41. // is keyboard input a standard (non-changing) VK keycode
  42. #define dIsStandardVK(c) (((0x08 <= (c)) && ((c) <= 0x12)) || \
  43. ((c) == 0x1b) || \
  44. ((0x20 <= (c)) && ((c) <= 0x2e)) || \
  45. ((0x30 <= (c)) && ((c) <= 0x39)) || \
  46. ((0x41 <= (c)) && ((c) <= 0x5a)) || \
  47. ((0x70 <= (c)) && ((c) <= 0x7B)))
  48. extern InputObjectInstances DIK_to_Key( U8 dikCode );
  49. extern U8 TranslateOSKeyCode(U8 vcode );
  50. extern InputModifiers convertModifierBits(const U32 in);
  51. static void _keyboardEvent(Win32Window* window,UINT message, WPARAM wParam, WPARAM lParam)
  52. {
  53. if(!initKBState)
  54. {
  55. dMemset(keyboardState, 0, sizeof(keyboardState));
  56. initKBState = true;
  57. }
  58. // Extract windows key info:
  59. // S32 repeatCount = (lParam & 0xffff);
  60. U32 scanCode = (lParam >> 16) & 0xff;
  61. bool extended = lParam & (1 << 24); // Enhanced keyboard key
  62. bool previous = lParam & (1 << 30); // Previously down
  63. bool make = (message == WM_KEYDOWN || message == WM_SYSKEYDOWN);
  64. // Translate the OS virtual key code to a Torque KEY_XXXX.
  65. S32 nVirtkey = TranslateOSKeyCode( wParam );
  66. S32 keyCode;
  67. if ( wParam == VK_PROCESSKEY && sgDoubleByteEnabled )
  68. keyCode = MapVirtualKey( scanCode, 1 ); // This is the REAL virtual key...
  69. else
  70. keyCode = wParam;
  71. // Convert alt/shift/ctrl to left or right variant if needed.
  72. S32 newVirtKey = nVirtkey;
  73. switch(nVirtkey)
  74. {
  75. case KEY_ALT:
  76. newVirtKey = extended ? KEY_RALT : KEY_LALT;
  77. break;
  78. case KEY_CONTROL:
  79. newVirtKey = extended ? KEY_RCONTROL : KEY_LCONTROL;
  80. break;
  81. case KEY_SHIFT:
  82. newVirtKey = (scanCode == 54) ? KEY_RSHIFT : KEY_LSHIFT;
  83. break;
  84. case KEY_RETURN:
  85. if ( extended )
  86. newVirtKey = KEY_NUMPADENTER;
  87. break;
  88. }
  89. // Track modifier keys
  90. U32 modifier = 0;
  91. switch (newVirtKey)
  92. {
  93. case KEY_LALT: modifier = IM_LALT; break;
  94. case KEY_RALT: modifier = IM_RALT; break;
  95. case KEY_LSHIFT: modifier = IM_LSHIFT; break;
  96. case KEY_RSHIFT: modifier = IM_RSHIFT; break;
  97. case KEY_LCONTROL: modifier = IM_LCTRL; break;
  98. case KEY_RCONTROL: modifier = IM_RCTRL; break;
  99. }
  100. if (make)
  101. {
  102. _ModifierKeys |= modifier;
  103. keyboardState[keyCode] |= 0x80;
  104. }
  105. else
  106. {
  107. _ModifierKeys &= ~modifier;
  108. keyboardState[keyCode] &= 0x7f;
  109. }
  110. U32 torqueMods = convertModifierBits( _ModifierKeys );
  111. Input::setModifierKeys( torqueMods );
  112. // If character event translation is active and this isn't a key
  113. // mapped in the global action map, try converting the event into
  114. // a character event first.
  115. if( make
  116. && window->getKeyboardTranslation()
  117. && !window->shouldNotTranslate( torqueMods, newVirtKey ) )
  118. {
  119. U16 chars[ 64 ];
  120. dMemset( chars, 0, sizeof( chars ) );
  121. S32 res = ToUnicode( keyCode, scanCode, keyboardState, chars, sizeof( chars ) / sizeof( chars[ 0 ] ), 0 );
  122. // This should only happen on Window 9x/ME systems
  123. if( res == 0 )
  124. res = ToAscii( keyCode, scanCode, keyboardState, chars, 0 );
  125. if( res >= 1 )
  126. {
  127. // Post chars, but filter them to not be control codes... this is a bit hacky.
  128. bool handledCharEvent = false;
  129. for( S32 i=0; i< res; i ++ )
  130. if( chars[i] >= 32)
  131. {
  132. window->charEvent.trigger(window->getWindowId(),_ModifierKeys,chars[i]);
  133. handledCharEvent = true;
  134. }
  135. if( handledCharEvent )
  136. return;
  137. }
  138. }
  139. // Produce a key event.
  140. U32 action = make ? (previous ? IA_REPEAT : IA_MAKE ) : IA_BREAK;
  141. window->keyEvent.trigger(window->getWindowId(),_ModifierKeys,action,newVirtKey);
  142. }
  143. //-----------------------------------------------------------------------------
  144. static bool _dispatch(HWND hWnd,UINT message,WPARAM wParam,WPARAM lParam)
  145. {
  146. static bool button[3] = {false,false,false};
  147. static S32 mouseNCState = -1; // -1 denotes unchanged,
  148. // 0 denotes changed but was hidden
  149. // 1 denotes changed but was visible
  150. Win32Window* window = hWnd?(Win32Window*)GetWindowLongPtr(hWnd, GWLP_USERDATA): 0;
  151. const WindowId devId = window ? window->getWindowId() : 0;
  152. // State tracking for focus/lose focus cursor management
  153. static bool cursorLocked = false;
  154. static bool cursorVisible = true;
  155. switch(message)
  156. {
  157. case WM_MOUSEMOVE:
  158. {
  159. // Skip it if we have no window!
  160. if (!window || !window->getCursorController())
  161. break;
  162. PlatformCursorController *pController = window->getCursorController();
  163. // If we're locked and unfocused, ignore it.
  164. if(window->shouldLockMouse() && !window->isFocused())
  165. break;
  166. // If the mouse was shown to accommodate a NC mouse move
  167. // we need to change it back to what it was
  168. if( mouseNCState != -1 )
  169. {
  170. pController->setCursorVisible( mouseNCState );
  171. mouseNCState = -1; // reset to unchanged
  172. }
  173. // Let the cursor manager update the native cursor.
  174. pController->refreshCursor();
  175. // Grab the mouse pos so we can modify it.
  176. S32 mouseX = S16(LOWORD(lParam));
  177. S32 mouseY = S16(HIWORD(lParam));
  178. // Ensure mouse lock when appropriate
  179. window->setMouseLocked( window->shouldLockMouse() );
  180. // Are we locked?
  181. if(window->isMouseLocked())
  182. {
  183. // Always invisible when locked.
  184. if( window->isCursorVisible() )
  185. window->setCursorVisible( false );
  186. RECT r;
  187. GetWindowRect(window->getHWND(), &r);
  188. // See Win32Window::setMouseLocked for explanation
  189. RECT rCopy = r;
  190. rCopy.top += 32; rCopy.bottom -= 64;
  191. rCopy.left += 32; rCopy.right -= 64;
  192. ClipCursor(&rCopy);
  193. // Recenter the mouse if necessary (don't flood the message pump)
  194. Point2I curPos;
  195. pController->getCursorPosition( curPos );
  196. const S32 centerX = (r.right + r.left) / 2;
  197. const S32 centerY = (r.bottom + r.top) / 2;
  198. if( curPos.x != centerX || curPos.y != centerY )
  199. pController->setCursorPosition(centerX, centerY);
  200. // Convert the incoming client pos into a screen pos, so we can
  201. // accurately convert to relative coordinates.
  202. POINT mousePos;
  203. mousePos.x = mouseX;
  204. mousePos.y = mouseY;
  205. ClientToScreen(window->getHWND(), &mousePos);
  206. // Now we can calculate the position relative to the center we set.
  207. mouseX = mousePos.x - centerX;
  208. mouseY = mousePos.y - centerY;
  209. }
  210. else
  211. {
  212. // Probably don't need to call this all the time but better
  213. // safe than sorry...
  214. ClipCursor(NULL);
  215. }
  216. window->mouseEvent.trigger(devId,_ModifierKeys,mouseX,mouseY,window->isMouseLocked());
  217. break;
  218. }
  219. // We want to show the system cursor whenever we leave
  220. // our window, and it'd be simple, except for one problem:
  221. // showcursor isn't a toggle. so, keep hammering it until
  222. // the cursor is *actually* going to be shown.
  223. case WM_NCMOUSEMOVE:
  224. {
  225. if( window )
  226. {
  227. mouseNCState = ( window->isCursorVisible() ? 1 : 0);
  228. window->setCursorVisible( true );
  229. }
  230. break;
  231. }
  232. case WM_LBUTTONDOWN:
  233. case WM_MBUTTONDOWN:
  234. case WM_RBUTTONDOWN: {
  235. S32 index = (message - WM_LBUTTONDOWN) / 3;
  236. button[index] = true;
  237. // Capture the mouse on button down to allow dragging outside
  238. // of the window boundary.
  239. if (GetCapture() != hWnd)
  240. SetCapture(hWnd);
  241. if (window)
  242. window->buttonEvent.trigger(devId,_ModifierKeys,IA_MAKE,index);
  243. break;
  244. }
  245. case WM_LBUTTONUP:
  246. case WM_MBUTTONUP:
  247. case WM_RBUTTONUP: {
  248. S32 index = (message - WM_LBUTTONUP) / 3;
  249. button[index] = false;
  250. // Release mouse capture from button down.
  251. if (!button[0] && !button[1] && !button[2])
  252. ReleaseCapture();
  253. if (window)
  254. window->buttonEvent.trigger(devId,_ModifierKeys,IA_BREAK,index);
  255. break;
  256. }
  257. case WM_MOUSEWHEEL: // Vertical wheel.
  258. if (window)
  259. window->wheelEvent.trigger(devId,_ModifierKeys,0,GET_WHEEL_DELTA_WPARAM(wParam));
  260. break;
  261. #ifdef WM_MOUSEHWHEEL // Vista
  262. case WM_MOUSEHWHEEL: // Horizontal wheel.
  263. if( window )
  264. window->wheelEvent.trigger( devId, _ModifierKeys, GET_WHEEL_DELTA_WPARAM( wParam ), 0 );
  265. break;
  266. #endif
  267. case WM_KEYUP:
  268. case WM_SYSKEYUP:
  269. case WM_KEYDOWN:
  270. case WM_SYSKEYDOWN:
  271. if (window)
  272. _keyboardEvent(window,message,wParam,lParam);
  273. break;
  274. // NOTE: if wParam is NOT equal to our window handle then we are GAINING focus
  275. case WM_SETFOCUS:
  276. // clear any key states
  277. _ModifierKeys = 0;
  278. dMemset(keyboardState, 0, 256);
  279. Input::setModifierKeys(0);
  280. // We must have a window present; otherwise there's nothing further
  281. // we can do about this event.
  282. if (window && window->getHWND() != (HWND)wParam)
  283. {
  284. if (cursorVisible == false)
  285. window->setCursorVisible(false);
  286. if (cursorLocked == true)
  287. window->setMouseLocked(true);
  288. // Update window state.
  289. window->setBackground(false);
  290. // Fire event.
  291. window->appEvent.trigger(devId, GainFocus);
  292. if (!Input::isActive())
  293. Input::activate();
  294. }
  295. break;
  296. // NOTE: if wParam is NOT equal to our window handle then we are LOSING focus
  297. case WM_KILLFOCUS:
  298. // clear any key states
  299. _ModifierKeys = 0;
  300. dMemset(keyboardState, 0, 256);
  301. Input::setModifierKeys(0);
  302. // We must have a window present; otherwise there's nothing further
  303. // we can do about this event.
  304. if (window && window->getHWND() != (HWND)wParam)
  305. {
  306. HWND hwnd = (HWND)wParam;
  307. UTF16 classBuf[256];
  308. if (hwnd)
  309. GetClassName(hwnd, classBuf, sizeof(classBuf));
  310. // We toggle the mouse lock when we become inactive
  311. // causing the subsequent lock call to defer itself
  312. // until the window becomes active again.
  313. if (window && window->isMouseLocked())
  314. {
  315. window->setMouseLocked( false );
  316. window->setMouseLocked( true );
  317. }
  318. // FIXME [tom, 5/1/2007] Hard coding this is lame since there's a const in win32Window.cpp
  319. // CodeReview - this fails if there is a second jug app in the arena.
  320. if (hwnd == NULL || dStrcmp(classBuf, L"TorqueJuggernaughtWindow") != 0)
  321. {
  322. // We are being made inactive and the window being made active isn't
  323. // a jugg window. Thus, we need to deactivate input.
  324. if (Input::isActive())
  325. Input::deactivate();
  326. }
  327. cursorVisible = window->isCursorVisible();
  328. if (!cursorVisible)
  329. window->setCursorVisible(true);
  330. cursorLocked = window->isMouseLocked();
  331. if (cursorLocked)
  332. window->setMouseLocked(false);
  333. // Update window state.
  334. window->setBackground(true);
  335. // Fire event.
  336. window->appEvent.trigger(devId, LoseFocus);
  337. }
  338. break;
  339. case WM_ACTIVATEAPP:
  340. if (wParam)
  341. {
  342. // Could extract current modifier state from windows.
  343. _ModifierKeys = 0;
  344. Input::setModifierKeys(_ModifierKeys);
  345. }
  346. break;
  347. case WM_CLOSE:
  348. if (window)
  349. window->appEvent.trigger(devId,WindowClose);
  350. // Force a quit if we're in play mode, otherwise there would be
  351. // no way to stop a journal playback.(
  352. if (Journal::IsPlaying())
  353. Process::requestShutdown();
  354. break;
  355. case WM_TIMER: {
  356. if (window)
  357. window->appEvent.trigger(devId,Timer);
  358. break;
  359. }
  360. case WM_DESTROY:{
  361. // Only people who care about this currently are web plugins, because
  362. // everyone else will just handle the WM_CLOSE app event.
  363. if(window)
  364. window->appEvent.trigger(devId,WindowDestroy);
  365. break;
  366. }
  367. case WM_QUIT: {
  368. // Quit indicates that we're not going to receive anymore Win32 messages.
  369. // Therefore, it's appropriate to flag our event loop for exit as well,
  370. // since we won't be getting any more messages.
  371. Process::requestShutdown();
  372. break;
  373. }
  374. // CodeReview - This is not used now and will incur an overhead for rendering
  375. // since the renderThreadBlocked fix requires handling WM_PAINT and
  376. // triggering the displayEvent. May need to revisit this at a later
  377. // time if we want event driven rendering.
  378. //case WM_PAINT: {
  379. // // Checking for isOpen will keep us from generating an event
  380. // // during the window creation process, which can cause problems
  381. // // with the journaling.
  382. // if (window && window->isOpen() && !winState.renderThreadBlocked )
  383. // window->displayEvent.trigger(devId);
  384. //}
  385. case WM_SIZE: {
  386. if (window && wParam != SIZE_MINIMIZED && !Journal::IsPlaying())
  387. {
  388. window->resizeEvent.trigger(window->getWindowId(), LOWORD(lParam),HIWORD(lParam));
  389. // Consume all existing mouse events and those posted to our own dispatch queue
  390. MSG msg;
  391. PeekMessage( &msg, 0,WM_MOUSEFIRST,WM_MOUSELAST , PM_QS_POSTMESSAGE | PM_NOYIELD | PM_REMOVE );
  392. RemoveMessages( NULL, WM_MOUSEMOVE, WM_MOUSEMOVE );
  393. if( window->isMouseLocked())
  394. {
  395. RECT r;
  396. GetWindowRect(window->getHWND(), &r);
  397. S32 centerX = (r.right + r.left) >> 1;
  398. S32 centerY = ((r.bottom + r.top) >> 1);
  399. window->setCursorPosition( centerX, centerY );
  400. // Set the CursorPos
  401. SetCursorPos(centerX, centerY);
  402. }
  403. }
  404. }
  405. }
  406. return true;
  407. }
  408. //-----------------------------------------------------------------------------
  409. // Structure used to store Windows events for delayed dispatching
  410. struct WinMessageQueue
  411. {
  412. public:
  413. struct Message {
  414. HWND hWnd;
  415. UINT message;
  416. WPARAM wparam;
  417. WPARAM lparam;
  418. };
  419. WinMessageQueue()
  420. {
  421. VECTOR_SET_ASSOCIATION( _messageList );
  422. }
  423. bool isEmpty() {
  424. return !_messageList.size();
  425. }
  426. void post(HWND hWnd,UINT message,WPARAM wparam,WPARAM lparam) {
  427. Message msg;
  428. msg.hWnd = hWnd;
  429. msg.message = message;
  430. msg.wparam = wparam;
  431. msg.lparam = lparam;
  432. _messageList.push_back(msg);
  433. }
  434. bool next(Message* msg) {
  435. if (!_messageList.size())
  436. return false;
  437. *msg = _messageList.first();
  438. _messageList.pop_front();
  439. return true;
  440. }
  441. void remove(HWND hWnd, UINT msgBegin = -1, UINT msgEnd = -1) {
  442. for (S32 i = 0; i < _messageList.size(); i++)
  443. {
  444. // Match Window
  445. if( hWnd != NULL && _messageList[i].hWnd == hWnd)
  446. _messageList.erase_fast(i--);
  447. else if( msgBegin != -1 && msgEnd != -1 )
  448. {
  449. // CodeReview - Match Message Range [6/30/2007 justind]
  450. //
  451. // Word of caution : Use this only if you know what you're doing.
  452. // I cannot be responsible for you blowing your leg off destroying
  453. // a bunch of messages you didn't intend to if you specify a ridiculous
  454. // range of messages values.
  455. //
  456. // To filter a single message, pass the message as the begin and end.
  457. if( _messageList[i].message >= msgBegin && _messageList[i].message <= msgEnd )
  458. _messageList.erase_fast(i--);
  459. }
  460. }
  461. }
  462. private:
  463. Vector<Message> _messageList;
  464. };
  465. static WinMessageQueue _MessageQueue;
  466. void RemoveMessages(HWND hWnd,UINT msgBegin,UINT msgEnd )
  467. {
  468. _MessageQueue.remove( hWnd, msgBegin, msgEnd );
  469. }
  470. // Dispatch the window event, or queue up for later
  471. void Dispatch(DispatchType type,HWND hWnd,UINT message,WPARAM wparam,WPARAM lparam)
  472. {
  473. // If the message queue is not empty, then we'll need to delay
  474. // this dispatch in order to preserve message order.
  475. if (type == DelayedDispatch || !_MessageQueue.isEmpty())
  476. _MessageQueue.post(hWnd,message,wparam,lparam);
  477. else
  478. _dispatch(hWnd,message,wparam,lparam);
  479. }
  480. // Dispatch next even in the queue
  481. bool DispatchNext()
  482. {
  483. WinMessageQueue::Message msg;
  484. if (!_MessageQueue.next(&msg))
  485. return false;
  486. _dispatch(msg.hWnd,msg.message,msg.wparam,msg.lparam);
  487. return true;
  488. }
  489. // Remove events from the queue
  490. void DispatchRemove(HWND hWnd)
  491. {
  492. _MessageQueue.remove(hWnd);
  493. }