winDispatch.cpp 17 KB

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