Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6501 lines
206 KiB

  1. /****************************** Module Header ******************************\
  2. * Module Name: ntinput.c
  3. *
  4. * Copyright (c) 1985 - 1999, Microsoft Corporation
  5. *
  6. * This module contains low-level input code specific to the NT
  7. * implementation of Win32 USER, which is mostly the interfaces to the
  8. * keyboard and mouse device drivers.
  9. *
  10. * History:
  11. * 11-26-90 DavidPe Created
  12. \***************************************************************************/
  13. #include "precomp.h"
  14. #pragma hdrstop
  15. #include <ntddmou.h>
  16. PKWAIT_BLOCK gWaitBlockArray;
  17. KEYBOARD_UNIT_ID_PARAMETER kuid;
  18. MOUSE_UNIT_ID_PARAMETER muid;
  19. typedef struct tagSCANCODEFLEXIBLEMAP {
  20. struct {
  21. BYTE bScanCode;
  22. BYTE bPrefix;
  23. BYTE abModifiers[6];
  24. } Orig;
  25. struct {
  26. BYTE bScanCode;
  27. BYTE bPrefix;
  28. BYTE abModifiers[6];
  29. } Target;
  30. } SCANCODEFLEXIBLEMAP, FAR *LPSCANCODEFLEXIBLEMAP;
  31. BYTE bLastVKDown = 0;
  32. int iLastMatchedTarget = -1;
  33. SCANCODEFLEXIBLEMAP* gpFlexMap;
  34. DWORD gdwFlexMapSize;
  35. VOID ProcessQueuedMouseEvents(VOID);
  36. #ifndef SUBPIXEL_MOUSE
  37. LONG DoMouseAccel(LONG delta);
  38. #endif
  39. VOID GetMouseCoord(LONG dx, LONG dy, DWORD dwFlags, LONG time, ULONG_PTR ExtraInfo, PPOINT ppt);
  40. VOID xxxMoveEventAbsolute(LONG x, LONG y, ULONG_PTR dwExtraInfo,
  41. #ifdef GENERIC_INPUT
  42. HANDLE hDevice,
  43. PMOUSE_INPUT_DATA pmei,
  44. #endif
  45. DWORD time,
  46. BOOL bInjected);
  47. VOID ProcessKeyboardInputWorker(PKEYBOARD_INPUT_DATA pkei,
  48. #ifdef GENERIC_INPUT
  49. PDEVICEINFO pDeviceInfo,
  50. #endif
  51. BOOL fProcessRemap);
  52. INT idxRemainder, idyRemainder;
  53. BYTE gbVKLastDown;
  54. /*
  55. * Mouse/Kbd diagnostics for #136483 etc. Remove when PNP is stable (IanJa)
  56. */
  57. #ifdef DIAGNOSE_IO
  58. ULONG gMouseProcessMiceInputTime = 0; // tick at start of ProcessMiceInput
  59. ULONG gMouseQueueMouseEventTime = 0; // tick at start of QueueMouseEvent
  60. ULONG gMouseUnqueueMouseEventTime = 0; // tick at start of UnqueueMouseEvent
  61. // Return a value as close as possible to the system's tick count,
  62. // yet guaranteed to be larger than the value returned last time.
  63. // (useful for sequencing events)
  64. // BUG: when NtGetTickCount overflows, the value returned by MonotonicTick
  65. // will not track system tick count well: instead it will increase by one
  66. // each time until it too overflows. (considerd harmless for IO DIAGNOSTICS)
  67. ULONG MonotonicTick()
  68. {
  69. static ULONG lasttick = 0;
  70. ULONG newtick;
  71. newtick = NtGetTickCount();
  72. if (newtick > lasttick) {
  73. lasttick = newtick; // use the new tick since it is larger
  74. } else {
  75. lasttick++; // artificially bump the tick up one.
  76. }
  77. return lasttick;
  78. }
  79. #endif
  80. /*
  81. * Parameter Constants for xxxButtonEvent()
  82. */
  83. #define MOUSE_BUTTON_LEFT 0x0001
  84. #define MOUSE_BUTTON_RIGHT 0x0002
  85. #define MOUSE_BUTTON_MIDDLE 0x0004
  86. #define MOUSE_BUTTON_X1 0x0008
  87. #define MOUSE_BUTTON_X2 0x0010
  88. #define ID_INPUT 0
  89. #define ID_MOUSE 1
  90. #define ID_TIMER 2
  91. #define ID_HIDCHANGE 3
  92. #define ID_SHUTDOWN 4
  93. #ifdef GENERIC_INPUT
  94. #define ID_TRUEHIDCHANGE 5
  95. #define ID_WDTIMER 6
  96. #define ID_NUMBER_HYDRA_REMOTE_HANDLES 7
  97. #else // GENERIC_INPUT
  98. #define ID_WDTIMER 5
  99. #define ID_NUMBER_HYDRA_REMOTE_HANDLES 6
  100. #endif // GENERIC_INPUT
  101. PKTIMER gptmrWD;
  102. PVOID *apObjects;
  103. /***************************************************************************\
  104. * fAbsoluteMouse
  105. *
  106. * Returns TRUE if the mouse event has absolute coordinates (as apposed to the
  107. * standard delta values we get from MS and PS2 mice)
  108. *
  109. * History:
  110. * 23-Jul-1992 JonPa Created.
  111. \***************************************************************************/
  112. #define fAbsoluteMouse( pmei ) \
  113. (((pmei)->Flags & MOUSE_MOVE_ABSOLUTE) != 0)
  114. /***************************************************************************\
  115. * ConvertToMouseDriverFlags
  116. *
  117. * Converts SendInput kind of flags to mouse driver flags as GetMouseCoord
  118. * needs them.
  119. * As mouse inputs are more frequent than send inputs, we penalize the later.
  120. *
  121. * History:
  122. * 17-dec-1997 MCostea Created.
  123. \***************************************************************************/
  124. #if ((MOUSEEVENTF_ABSOLUTE >> 15) ^ MOUSE_MOVE_ABSOLUTE) || \
  125. ((MOUSEEVENTF_VIRTUALDESK >> 13) ^ MOUSE_VIRTUAL_DESKTOP)
  126. # error("Bit mapping broken: fix ConvertToMouseDriverFlags")
  127. #endif
  128. #define ConvertToMouseDriverFlags( Flags ) \
  129. (((Flags) & MOUSEEVENTF_ABSOLUTE) >> 15 | \
  130. ((Flags) & MOUSEEVENTF_VIRTUALDESK) >> 13)
  131. #define VKTOMODIFIERS(Vk) ((((Vk) >= VK_SHIFT) && ((Vk) <= VK_MENU)) ? \
  132. (MOD_SHIFT >> ((Vk) - VK_SHIFT)) : \
  133. 0)
  134. #if (VKTOMODIFIERS(VK_SHIFT) != MOD_SHIFT) || \
  135. (VKTOMODIFIERS(VK_CONTROL) != MOD_CONTROL) || \
  136. (VKTOMODIFIERS(VK_MENU) != MOD_ALT)
  137. # error("VKTOMODIFIERS broken")
  138. #endif
  139. /***************************************************************************\
  140. * xxxInitInput
  141. *
  142. * This function is called from CreateTerminalInput() and gets USER setup to
  143. * process keyboard and mouse input. It starts the RIT for that terminal.
  144. * History:
  145. * 11-26-90 DavidPe Created.
  146. \***************************************************************************/
  147. BOOL xxxInitInput(
  148. PTERMINAL pTerm)
  149. {
  150. NTSTATUS Status;
  151. USER_API_MSG m;
  152. RIT_INIT initData;
  153. UserAssert(pTerm != NULL);
  154. #ifdef MOUSE_LOCK_CODE
  155. /*
  156. * Lock RIT pages into memory
  157. */
  158. LockMouseInputCodePages();
  159. #endif
  160. initData.pTerm = pTerm;
  161. initData.pRitReadyEvent = CreateKernelEvent(SynchronizationEvent, FALSE);
  162. if (initData.pRitReadyEvent == NULL) {
  163. return FALSE;
  164. }
  165. /*
  166. * Create the RIT and let it run.
  167. */
  168. if (!InitCreateSystemThreadsMsg(&m, CST_RIT, &initData, 0, FALSE)) {
  169. FreeKernelEvent(&initData.pRitReadyEvent);
  170. return FALSE;
  171. }
  172. /*
  173. * Be sure that we are not in CSRSS context.
  174. * WARNING: If for any reason we changed this to run in CSRSS context then we have to use
  175. * LpcRequestPort instead of LpcRequestWaitReplyPort.
  176. */
  177. UserAssert (!ISCSRSS());
  178. LeaveCrit();
  179. Status = LpcRequestWaitReplyPort(CsrApiPort, (PPORT_MESSAGE)&m, (PPORT_MESSAGE)&m);
  180. if (!NT_SUCCESS(Status)) {
  181. goto Exit;
  182. }
  183. KeWaitForSingleObject(initData.pRitReadyEvent, WrUserRequest,
  184. KernelMode, FALSE, NULL);
  185. Exit:
  186. FreeKernelEvent(&initData.pRitReadyEvent);
  187. EnterCrit();
  188. return (gptiRit != NULL);
  189. }
  190. /***************************************************************************\
  191. * InitScancodeMap
  192. *
  193. * Fetches the scancode map from the registry, allocating space as required.
  194. *
  195. * A scancode map is used to convert unusual OEM scancodes into standard
  196. * "Scan Code Set 1" values. This is to support KB3270 keyboards, but can
  197. * be used for other types too.
  198. *
  199. * History:
  200. * 96-04-18 IanJa Created.
  201. \***************************************************************************/
  202. const WCHAR gwszScancodeMap[] = L"Scancode Map";
  203. const WCHAR gwszScancodeMapEx[] = L"Scancode Map Ex";
  204. VOID InitScancodeMap(
  205. PUNICODE_STRING pProfileName)
  206. {
  207. DWORD dwBytes;
  208. UINT idSection;
  209. PUNICODE_STRING pPN;
  210. LPBYTE pb;
  211. TAGMSG2(DBGTAG_KBD, "InitScancodeMap with pProfileName=%#p, \"%S\"", pProfileName,
  212. pProfileName ? pProfileName->Buffer : L"");
  213. if (gpScancodeMap) {
  214. UserFreePool(gpScancodeMap);
  215. gpScancodeMap = NULL;
  216. }
  217. /*
  218. * Read basic scancode mapping information.
  219. * Firstly try per user, and then per system.
  220. */
  221. idSection = PMAP_UKBDLAYOUT;
  222. pPN = pProfileName;
  223. dwBytes = FastGetProfileValue(pPN, idSection, gwszScancodeMap, NULL, NULL, 0, 0);
  224. if (dwBytes == 0) {
  225. idSection = PMAP_KBDLAYOUT;
  226. pPN = NULL;
  227. dwBytes = FastGetProfileValue(pPN, idSection, gwszScancodeMap, NULL, NULL, 0, 0);
  228. }
  229. if (dwBytes > sizeof(SCANCODEMAP)) {
  230. pb = UserAllocPoolZInit(dwBytes, TAG_SCANCODEMAP);
  231. if (pb) {
  232. dwBytes = FastGetProfileValue(pPN, idSection, gwszScancodeMap, NULL, pb, dwBytes, 0);
  233. gpScancodeMap = (SCANCODEMAP*)pb;
  234. }
  235. }
  236. /*
  237. * Read extended scancode mapping information.
  238. * Firstly try per user, then per system.
  239. */
  240. if (gpFlexMap) {
  241. UserFreePool(gpFlexMap);
  242. gpFlexMap = NULL;
  243. gdwFlexMapSize = 0;
  244. }
  245. idSection = PMAP_UKBDLAYOUT;
  246. pPN = pProfileName;
  247. dwBytes = FastGetProfileValue(pPN, idSection, gwszScancodeMapEx, NULL, NULL, 0, 0);
  248. if (dwBytes == 0) {
  249. TAGMSG0(DBGTAG_KBD, "InitScancodeMap: mapex is not in per-user profile. will use the system's");
  250. idSection = PMAP_KBDLAYOUT;
  251. pPN = NULL;
  252. dwBytes = FastGetProfileValue(pPN, idSection, gwszScancodeMapEx, NULL, NULL, 0, 0);
  253. }
  254. if (dwBytes >= sizeof(SCANCODEFLEXIBLEMAP) && dwBytes % sizeof(SCANCODEFLEXIBLEMAP) == 0) {
  255. if ((pb = UserAllocPoolZInit(dwBytes, TAG_SCANCODEMAP)) != NULL) {
  256. dwBytes = FastGetProfileValue(pPN, idSection, gwszScancodeMapEx, NULL, pb, dwBytes, 0);
  257. gpFlexMap = (SCANCODEFLEXIBLEMAP*)pb;
  258. gdwFlexMapSize = dwBytes / sizeof(SCANCODEFLEXIBLEMAP);
  259. }
  260. }
  261. #if DBG
  262. else if (dwBytes != 0) {
  263. TAGMSG1(DBGTAG_KBD, "InitScancodeMap: incorrect dwSize(0x%x) specified.", dwBytes);
  264. }
  265. #endif
  266. }
  267. /***************************************************************************\
  268. * MapScancode
  269. *
  270. * Converts a scancode (and it's prefix, if any) to a different scancode
  271. * and prefix.
  272. *
  273. * Parameters:
  274. * pbScanCode = address of Scancode byte, the scancode may be changed
  275. * pbPrefix = address of Prefix byte, The prefix may be changed
  276. *
  277. * Return value:
  278. * TRUE - mapping was found, scancode was altered.
  279. * FALSE - no mapping found, scancode was not altered.
  280. *
  281. * Note on scancode map table format:
  282. * A table entry DWORD of 0xE0450075 means scancode 0x45, prefix 0xE0
  283. * gets mapped to scancode 0x75, no prefix
  284. *
  285. * History:
  286. * 96-04-18 IanJa Created.
  287. \***************************************************************************/
  288. PKBDTABLES GetCurrentKbdTables()
  289. {
  290. PKBDTABLES pKbdTbl;
  291. PTHREADINFO pti;
  292. CheckCritIn();
  293. if (gpqForeground == NULL) {
  294. TAGMSG0(DBGTAG_KBD, "GetCurrentKbdTables: NULL gpqForeground\n");
  295. return NULL;
  296. }
  297. pti = PtiKbdFromQ(gpqForeground);
  298. UserAssert(pti);
  299. if (pti->spklActive) {
  300. pKbdTbl = pti->spklActive->spkf->pKbdTbl;
  301. } else {
  302. RIPMSG0(RIP_WARNING, "SendKeyUpDown: NULL spklActive\n");
  303. pKbdTbl = gpKbdTbl;
  304. }
  305. UserAssert(pKbdTbl);
  306. return pKbdTbl;
  307. }
  308. VOID SendKeyUpDown(
  309. CONST BYTE bVK,
  310. CONST BOOLEAN fBreak)
  311. {
  312. KE ke;
  313. PKBDTABLES pKbdTbl;
  314. CheckCritIn();
  315. ke.dwTime = 0;
  316. ke.usFlaggedVk = bVK | KBDMAPPEDVK;
  317. if (fBreak) {
  318. ke.usFlaggedVk |= KBDBREAK;
  319. }
  320. //
  321. // If scancode is not specified (==0), we need to
  322. // find the scancode value from the virtual key code.
  323. //
  324. pKbdTbl = GetCurrentKbdTables();
  325. if (pKbdTbl) {
  326. ke.bScanCode = (BYTE)InternalMapVirtualKeyEx(bVK, 0, pKbdTbl);
  327. }
  328. TAGMSG1(DBGTAG_KBD, "Sending Key for VK=%04x", ke.usFlaggedVk);
  329. xxxProcessKeyEvent(&ke, 0, TRUE);
  330. }
  331. __inline VOID SendKeyDown(
  332. CONST BYTE bVK)
  333. {
  334. SendKeyUpDown(bVK, FALSE);
  335. }
  336. __inline VOID SendKeyUp(
  337. CONST BYTE bVK)
  338. {
  339. SendKeyUpDown(bVK, TRUE);
  340. }
  341. BOOL IsKeyDownSpecified(CONST BYTE bVK, CONST BYTE* pbMod)
  342. {
  343. int i;
  344. for (i = 0; i < sizeof((SCANCODEFLEXIBLEMAP*)NULL)->Orig.abModifiers && pbMod[i]; ++i) {
  345. if (bVK == pbMod[i]) {
  346. return TRUE;
  347. }
  348. }
  349. return FALSE;
  350. }
  351. BOOL MapFlexibleKeys(PKE pke, CONST BYTE bPrefix
  352. #ifdef GENERIC_INPUT
  353. , PDEVICEINFO pDeviceInfo
  354. #endif
  355. )
  356. {
  357. UINT i;
  358. static const BYTE abModifiers[] = {
  359. VK_LCONTROL, VK_RCONTROL,
  360. VK_LSHIFT, VK_RSHIFT,
  361. VK_LMENU, VK_RMENU,
  362. VK_LWIN, VK_RWIN,
  363. VK_APPS, VK_CAPITAL,
  364. };
  365. for (i = 0; i < gdwFlexMapSize; ++i) {
  366. if (gpFlexMap[i].Orig.bPrefix == bPrefix && gpFlexMap[i].Orig.bScanCode == pke->bScanCode) {
  367. UINT j;
  368. if ((pke->usFlaggedVk & KBDBREAK) && i == (UINT)iLastMatchedTarget) {
  369. //
  370. // If this is a keyup event, and if it matches the last substituted
  371. // key, we want to send keyup event right away.
  372. //
  373. iLastMatchedTarget = -1;
  374. break;
  375. }
  376. for (j = 0; j < ARRAY_SIZE(abModifiers); ++j) {
  377. BYTE bVK = abModifiers[j];
  378. if (bVK == bLastVKDown) {
  379. //
  380. // Ignore the key if it's previously substituted by us.
  381. //
  382. bLastVKDown = 0;
  383. continue;
  384. }
  385. if (!TestKeyDownBit(gafRawKeyState, bVK) == IsKeyDownSpecified(bVK, gpFlexMap[i].Orig.abModifiers)) {
  386. TAGMSG1(DBGTAG_KBD, "MapFlexibleKeys: not match by vk=%02x", bVK);
  387. // No match!
  388. break;
  389. }
  390. }
  391. if (j >= ARRAY_SIZE(abModifiers)) {
  392. // We found the match. Now break the loop.
  393. TAGMSG1(DBGTAG_KBD, "MapFlexibleKeys: found a match for sc=%02x", gpFlexMap[i].Orig.bScanCode);
  394. break;
  395. }
  396. }
  397. }
  398. if (i < gdwFlexMapSize) {
  399. KEYBOARD_INPUT_DATA kei;
  400. UINT j, nUp = 0, nDown = 0;
  401. BYTE bVKModUp[ARRAY_SIZE(((SCANCODEFLEXIBLEMAP*)NULL)->Orig.abModifiers)];
  402. BYTE bVKModDown[ARRAY_SIZE(((SCANCODEFLEXIBLEMAP*)NULL)->Target.abModifiers)];
  403. // We found it.
  404. // Yes, this key.
  405. TAGMSG3(DBGTAG_KBD, "MapFlexibleKeys: found a match %d (prefix=%x, sc=%x).", i, gpFlexMap[i].Orig.bPrefix, gpFlexMap[i].Orig.bScanCode);
  406. //
  407. // If this is a keydown event, we want to simulate
  408. // the modifier keys.
  409. //
  410. if ((pke->usFlaggedVk & KBDBREAK) == 0) {
  411. //
  412. // Now we need to adjust the down state of the modifieres, which is currently
  413. // pressed but not specified in the substitute.
  414. // For instance, if CTRL key is pressed now, but if CTRL is not specified in the substitute
  415. // modifiers list, we need to make an artificial keyup so that we'll be able to fake the
  416. // situation. Of cource, we need to push CTRL key after we finish remapping.
  417. //
  418. for (j = 0; j < ARRAY_SIZE(gpFlexMap[i].Orig.abModifiers) && gpFlexMap[i].Orig.abModifiers[j]; ++j) {
  419. if (!IsKeyDownSpecified(gpFlexMap[i].Orig.abModifiers[j], gpFlexMap[i].Target.abModifiers)) {
  420. //
  421. // We need to send UP key for this one.
  422. //
  423. bVKModUp[nUp++] = gpFlexMap[i].Orig.abModifiers[j];
  424. SendKeyUp(gpFlexMap[i].Orig.abModifiers[j]);
  425. }
  426. }
  427. for (j = 0; j < ARRAY_SIZE(gpFlexMap[i].Target.abModifiers) && gpFlexMap[i].Target.abModifiers[i]; ++j) {
  428. if (!IsKeyDownSpecified(gpFlexMap[i].Target.abModifiers[j], gpFlexMap[i].Orig.abModifiers)) {
  429. //
  430. // We need to send DOWN key for this one.
  431. //
  432. bVKModDown[nDown++] = gpFlexMap[i].Target.abModifiers[j];
  433. SendKeyDown(gpFlexMap[i].Target.abModifiers[j]);
  434. }
  435. }
  436. }
  437. //
  438. // Now we are ready to send the substituted key.
  439. //
  440. kei.ExtraInformation = 0;
  441. kei.Flags = 0;
  442. if (gpFlexMap[i].Target.bPrefix == 0xE0) {
  443. kei.Flags |= KEY_E0;
  444. } else if (gpFlexMap[i].Target.bPrefix == 0xE1) {
  445. kei.Flags |= KEY_E1;
  446. }
  447. if (pke->usFlaggedVk & KBDBREAK) {
  448. kei.Flags |= KEY_BREAK;
  449. }
  450. kei.MakeCode = gpFlexMap[i].Target.bScanCode;
  451. kei.UnitId = 0; // LATER:
  452. TAGMSG2(DBGTAG_KBD, "MapFlexibleKeys: injecting sc=%02x (flag=%x)",
  453. kei.MakeCode, kei.Flags);
  454. ProcessKeyboardInputWorker(&kei,
  455. #ifdef GENERIC_INPUT
  456. pDeviceInfo,
  457. #endif
  458. FALSE);
  459. if ((pke->usFlaggedVk & KBDBREAK) == 0) {
  460. //
  461. // Remember the last down key generated by me.
  462. // This will be used when matching the UP key.
  463. //
  464. bLastVKDown = gbVKLastDown;
  465. iLastMatchedTarget = i;
  466. }
  467. //
  468. // Restore the orignial modifier state.
  469. //
  470. for (j = 0; j < nUp; ++j) {
  471. SendKeyDown(bVKModUp[j]);
  472. }
  473. for (j = 0; j < nDown; ++j) {
  474. SendKeyUp(bVKModDown[j]);
  475. }
  476. //
  477. // Tell the caller we processed this key. The caller should
  478. // not continue handling this key if this function returns FALSE.
  479. //
  480. return FALSE;
  481. }
  482. return TRUE;
  483. }
  484. BOOL
  485. MapScancode(
  486. PKE pke,
  487. PBYTE pbPrefix
  488. #ifdef GENERIC_INPUT
  489. ,
  490. PDEVICEINFO pDeviceInfo
  491. #endif
  492. )
  493. {
  494. if (gpScancodeMap) {
  495. DWORD *pdw;
  496. WORD wT = MAKEWORD(pke->bScanCode, *pbPrefix);
  497. CheckCritIn();
  498. UserAssert(gpScancodeMap != NULL);
  499. for (pdw = &(gpScancodeMap->dwMap[0]); *pdw; pdw++) {
  500. if (HIWORD(*pdw) == wT) {
  501. wT = LOWORD(*pdw);
  502. pke->bScanCode = LOBYTE(wT);
  503. *pbPrefix = HIBYTE(wT);
  504. break;
  505. }
  506. }
  507. }
  508. return IsRemoteConnection() ||
  509. MapFlexibleKeys(pke, *pbPrefix
  510. #ifdef GENERIC_INPUT
  511. , pDeviceInfo
  512. #endif
  513. );
  514. }
  515. /***************************************************************************\
  516. * InitMice
  517. *
  518. * This function initializes the data and settings before we start enumerating
  519. * the mice.
  520. *
  521. * History:
  522. * 11-18-97 IanJa Created.
  523. \***************************************************************************/
  524. VOID InitMice()
  525. {
  526. CLEAR_ACCF(ACCF_MKVIRTUALMOUSE);
  527. CLEAR_GTERMF(GTERMF_MOUSE);
  528. SYSMET(MOUSEPRESENT) = FALSE;
  529. SYSMET(CMOUSEBUTTONS) = 0;
  530. SYSMET(MOUSEWHEELPRESENT) = FALSE;
  531. }
  532. /***************************************************************************\
  533. * FreeDeviceInfo
  534. *
  535. * Unlinks a DEVICEINFO struct from the gpDeviceInfoList list and frees the
  536. * allocated memory UNLESS the device is actively being read (GDIF_READING) or
  537. * has a PnP thread waiting for it in RequestDeviceChange() (GDIAF_PNPWAITING)
  538. * If the latter, then wake the PnP thread via pkeHidChangeCompleted so that it
  539. * can free the structure itself.
  540. *
  541. * Returns a pointer to the next DEVICEINFO struct, or NULL if the device was
  542. * not found in the gpDeviceInfoList.
  543. *
  544. * History:
  545. * 11-18-97 IanJa Created.
  546. \***************************************************************************/
  547. PDEVICEINFO FreeDeviceInfo(PDEVICEINFO pDeviceInfo)
  548. {
  549. PDEVICEINFO *ppDeviceInfo;
  550. CheckDeviceInfoListCritIn();
  551. TAGMSG1(DBGTAG_PNP, "FreeDeviceInfo(%#p)", pDeviceInfo);
  552. /*
  553. * We cannot free the device since we still have a read pending.
  554. * Mark it GDIAF_FREEME so that it will be freed when the APC is made
  555. * (see InputApc), or when the next read request is about to be issued
  556. * (see StartDeviceRead).
  557. */
  558. if (pDeviceInfo->bFlags & GDIF_READING) {
  559. #if DIAGNOSE_IO
  560. pDeviceInfo->bFlags |= GDIF_READERMUSTFREE;
  561. #endif
  562. TAGMSG1(DBGTAG_PNP, "** FreeDeviceInfo(%#p) DEFERRED : reader must free", pDeviceInfo);
  563. pDeviceInfo->usActions |= GDIAF_FREEME;
  564. #ifdef TRACK_PNP_NOTIFICATION
  565. if (gfRecordPnpNotification) {
  566. RecordPnpNotification(PNP_NTF_FREEDEVICEINFO_DEFERRED, pDeviceInfo, pDeviceInfo->usActions);
  567. }
  568. #endif
  569. return pDeviceInfo->pNext;
  570. }
  571. /*
  572. * If a PnP thread is waiting in RequestDeviceChange for some action to be
  573. * performed on this device, just mark it for freeing and signal that PnP
  574. * thread with the pkeHidChangeCompleted so that it will free it
  575. */
  576. #ifdef GENERIC_INPUT
  577. /*
  578. * Now that pDeviceInfo is handle based, if we don't own the user critical section.
  579. * we mark it to be freed later on and have to bail out,
  580. */
  581. if ((pDeviceInfo->usActions & GDIAF_PNPWAITING) || !ExIsResourceAcquiredExclusiveLite(gpresUser))
  582. #else
  583. if (pDeviceInfo->usActions & GDIAF_PNPWAITING)
  584. #endif
  585. {
  586. #if DIAGNOSE_IO
  587. pDeviceInfo->bFlags |= GDIF_PNPMUSTFREE;
  588. #endif
  589. TAGMSG1(DBGTAG_PNP, "** FreeDeviceInfo(%#p) DEFERRED : PnP must free", pDeviceInfo);
  590. pDeviceInfo->usActions |= GDIAF_FREEME;
  591. KeSetEvent(pDeviceInfo->pkeHidChangeCompleted, EVENT_INCREMENT, FALSE);
  592. return pDeviceInfo->pNext;
  593. }
  594. #ifdef TRACK_PNP_NOTIFICATION
  595. if (gfRecordPnpNotification) {
  596. RecordPnpNotification(PNP_NTF_FREEDEVICEINFO, pDeviceInfo, pDeviceInfo->usActions);
  597. }
  598. #endif
  599. #ifdef GENERIC_INPUT
  600. CheckCritIn();
  601. #endif
  602. ppDeviceInfo = &gpDeviceInfoList;
  603. while (*ppDeviceInfo) {
  604. if (*ppDeviceInfo == pDeviceInfo
  605. #ifdef GENERIC_INPUT
  606. && HMMarkObjectDestroy(pDeviceInfo)
  607. #endif
  608. ) {
  609. /*
  610. * Found the DEVICEINFO struct, so free it and its members.
  611. */
  612. if (pDeviceInfo->pkeHidChangeCompleted != NULL) {
  613. // N.b. the timing could be pretty critical around this
  614. FreeKernelEvent(&pDeviceInfo->pkeHidChangeCompleted);
  615. }
  616. if (pDeviceInfo->ustrName.Buffer != NULL) {
  617. UserFreePool(pDeviceInfo->ustrName.Buffer);
  618. }
  619. #ifdef GENERIC_INPUT
  620. if (pDeviceInfo->type == DEVICE_TYPE_HID) {
  621. CheckCritIn();
  622. /*
  623. * Unlock the device request list
  624. */
  625. UserAssert(pDeviceInfo->hid.pTLCInfo);
  626. if (--pDeviceInfo->hid.pTLCInfo->cDevices == 0) {
  627. if (!HidTLCActive(pDeviceInfo->hid.pTLCInfo)) {
  628. // Nobody is interested in this device anymore
  629. FreeHidTLCInfo(pDeviceInfo->hid.pTLCInfo);
  630. }
  631. }
  632. /*
  633. * Unlock the HID descriptor
  634. */
  635. UserAssert(pDeviceInfo->hid.pHidDesc);
  636. FreeHidDesc(pDeviceInfo->hid.pHidDesc);
  637. }
  638. #endif
  639. *ppDeviceInfo = pDeviceInfo->pNext;
  640. #ifdef GENERIC_INPUT
  641. TAGMSG1(DBGTAG_PNP, "FreeDeviceInfo: freeing deviceinfo=%#p", pDeviceInfo);
  642. HMFreeObject(pDeviceInfo);
  643. #else
  644. UserFreePool(pDeviceInfo);
  645. #endif
  646. return *ppDeviceInfo;
  647. }
  648. ppDeviceInfo = &(*ppDeviceInfo)->pNext;
  649. }
  650. RIPMSG1(RIP_ERROR, "pDeviceInfo %#p not found in gpDeviceInfoList", pDeviceInfo);
  651. return NULL;
  652. }
  653. /***************************************************************************\
  654. * UpdateMouseInfo
  655. *
  656. * This function updates mouse information for a remote session.
  657. *
  658. * History:
  659. * 05-22-98 clupu Created.
  660. \***************************************************************************/
  661. VOID UpdateMouseInfo(
  662. VOID)
  663. {
  664. DEVICEINFO *pDeviceInfo;
  665. CheckCritIn(); // expect no surprises
  666. UserAssert(IsRemoteConnection());
  667. if (ghRemoteMouseChannel == NULL) {
  668. return;
  669. }
  670. UserAssert(gnMice == 1);
  671. /*
  672. * Mark the mice and signal the RIT to do the work asynchronously
  673. */
  674. EnterDeviceInfoListCrit();
  675. for (pDeviceInfo = gpDeviceInfoList; pDeviceInfo; pDeviceInfo = pDeviceInfo->pNext) {
  676. if (pDeviceInfo->type == DEVICE_TYPE_MOUSE) {
  677. TAGMSG1(DBGTAG_PNP, "UpdateMouseInfo(): pDeviceInfo %#p ARRIVED", pDeviceInfo);
  678. RequestDeviceChange(pDeviceInfo, GDIAF_ARRIVED | GDIAF_RECONNECT, TRUE);
  679. }
  680. }
  681. LeaveDeviceInfoListCrit();
  682. }
  683. NTSTATUS DeviceNotify(IN PPLUGPLAY_NOTIFY_HDR, IN PDEVICEINFO);
  684. /*
  685. * The below two routines are transplanted from i8042prt
  686. * to get the BIOS NumLock status.
  687. */
  688. typedef struct _LED_INFO {
  689. USHORT usLedFlags;
  690. BOOLEAN fFound;
  691. } LED_INFO, *PLED_INFO;
  692. /****************************************************************************
  693. *
  694. * Routine Description:
  695. *
  696. * This is the callout routine sent as a parameter to
  697. * IoQueryDeviceDescription. It grabs the keyboard peripheral configuration
  698. * information.
  699. *
  700. * Arguments:
  701. *
  702. * Context - Context parameter that was passed in by the routine
  703. * that called IoQueryDeviceDescription.
  704. *
  705. * PathName - The full pathname for the registry key.
  706. *
  707. * BusType - Bus interface type (Isa, Eisa, Mca, etc.).
  708. *
  709. * BusNumber - The bus sub-key (0, 1, etc.).
  710. *
  711. * BusInformation - Pointer to the array of pointers to the full value
  712. * information for the bus.
  713. *
  714. * ControllerType - The controller type (should be KeyboardController).
  715. *
  716. * ControllerNumber - The controller sub-key (0, 1, etc.).
  717. *
  718. * ControllerInformation - Pointer to the array of pointers to the full
  719. * value information for the controller key.
  720. *
  721. * PeripheralType - The peripheral type (should be KeyboardPeripheral).
  722. *
  723. * PeripheralNumber - The peripheral sub-key.
  724. *
  725. * PeripheralInformation - Pointer to the array of pointers to the full
  726. * value information for the peripheral key.
  727. *
  728. *
  729. * Return Value:
  730. *
  731. * None. If successful, will have the following side-effects:
  732. *
  733. * - Sets DeviceObject->DeviceExtension->HardwarePresent.
  734. * - Sets configuration fields in
  735. * DeviceObject->DeviceExtension->Configuration.
  736. *
  737. ****************************************************************************/
  738. NTSTATUS
  739. KeyboardDeviceSpecificCallout(
  740. IN PVOID Context,
  741. IN PUNICODE_STRING PathName,
  742. IN INTERFACE_TYPE BusType,
  743. IN ULONG BusNumber,
  744. IN PKEY_VALUE_FULL_INFORMATION *BusInformation,
  745. IN CONFIGURATION_TYPE ControllerType,
  746. IN ULONG ControllerNumber,
  747. IN PKEY_VALUE_FULL_INFORMATION *ControllerInformation,
  748. IN CONFIGURATION_TYPE PeripheralType,
  749. IN ULONG PeripheralNumber,
  750. IN PKEY_VALUE_FULL_INFORMATION *PeripheralInformation)
  751. {
  752. PUCHAR pPeripheralData;
  753. PCM_PARTIAL_RESOURCE_DESCRIPTOR pResDesc;
  754. PCM_KEYBOARD_DEVICE_DATA pKbdDeviceData;
  755. PLED_INFO pInfo;
  756. ULONG i, listCount;
  757. TAGMSG0(DBGTAG_KBD, "KeyboardDeviceSpecificCallout: called.");
  758. UNREFERENCED_PARAMETER(PathName);
  759. UNREFERENCED_PARAMETER(BusType);
  760. UNREFERENCED_PARAMETER(BusNumber);
  761. UNREFERENCED_PARAMETER(BusInformation);
  762. UNREFERENCED_PARAMETER(ControllerType);
  763. UNREFERENCED_PARAMETER(ControllerNumber);
  764. UNREFERENCED_PARAMETER(ControllerInformation);
  765. UNREFERENCED_PARAMETER(PeripheralType);
  766. UNREFERENCED_PARAMETER(PeripheralNumber);
  767. pInfo = (PLED_INFO)Context;
  768. if (pInfo->fFound) {
  769. return STATUS_SUCCESS;
  770. }
  771. //
  772. // Look through the peripheral's resource list for device-specific
  773. // information.
  774. //
  775. if (PeripheralInformation[IoQueryDeviceConfigurationData]->DataLength != 0) {
  776. pPeripheralData =
  777. ((PUCHAR)(PeripheralInformation[IoQueryDeviceConfigurationData])) +
  778. PeripheralInformation[IoQueryDeviceConfigurationData]->DataOffset;
  779. pPeripheralData += FIELD_OFFSET(CM_FULL_RESOURCE_DESCRIPTOR, PartialResourceList);
  780. listCount = ((PCM_PARTIAL_RESOURCE_LIST)pPeripheralData)->Count;
  781. pResDesc = ((PCM_PARTIAL_RESOURCE_LIST)pPeripheralData)->PartialDescriptors;
  782. for (i = 0; i < listCount; i++, pResDesc++) {
  783. if (pResDesc->Type == CmResourceTypeDeviceSpecific) {
  784. //
  785. // Get the keyboard type, subtype, and the initial
  786. // settings for the LEDs.
  787. //
  788. pKbdDeviceData = (PCM_KEYBOARD_DEVICE_DATA)
  789. (((PUCHAR) pResDesc) + sizeof(CM_PARTIAL_RESOURCE_DESCRIPTOR));
  790. TAGMSG1(DBGTAG_KBD, "KeyboardDeviceSpecificCallout: specific data is %p\n", pKbdDeviceData);
  791. #ifdef LATER
  792. if (pKbdDeviceData->Type <= NUM_KNOWN_KEYBOARD_TYPES) {
  793. pInfo->KeyboardExtension->KeyboardAttributes.KeyboardIdentifier.Type =
  794. pKbdDeviceData->Type;
  795. }
  796. pInfo->KeyboardExtension->KeyboardAttributes.KeyboardIdentifier.Subtype =
  797. pKbdDeviceData->Subtype;
  798. #endif
  799. pInfo->usLedFlags = (pKbdDeviceData->KeyboardFlags >> 4) &
  800. (KEYBOARD_SCROLL_LOCK_ON | KEYBOARD_NUM_LOCK_ON | KEYBOARD_CAPS_LOCK_ON);
  801. TAGMSG1(DBGTAG_KBD, "KeyboardDeviceSpecificCallout: LED %04x", pInfo->usLedFlags);
  802. pInfo->fFound = TRUE;
  803. break;
  804. }
  805. }
  806. }
  807. return STATUS_SUCCESS;
  808. }
  809. VOID GetBiosNumLockStatus(
  810. VOID)
  811. {
  812. LED_INFO info;
  813. INTERFACE_TYPE interfaceType;
  814. CONFIGURATION_TYPE controllerType = KeyboardController;
  815. CONFIGURATION_TYPE peripheralType = KeyboardPeripheral;
  816. ULONG i;
  817. info.usLedFlags = 0;
  818. info.fFound = FALSE;
  819. for (i = 0; i < MaximumInterfaceType; i++) {
  820. //
  821. // Get the registry information for this device.
  822. //
  823. interfaceType = i;
  824. IoQueryDeviceDescription(&interfaceType,
  825. NULL,
  826. &controllerType,
  827. NULL,
  828. &peripheralType,
  829. NULL,
  830. KeyboardDeviceSpecificCallout,
  831. (PVOID)&info);
  832. if (info.fFound) {
  833. gklpBootTime.LedFlags = info.usLedFlags;
  834. return;
  835. }
  836. }
  837. RIPMSG0(RIP_WARNING, "GetBiosNumLockStatus: could not find the BIOS LED info!!!");
  838. }
  839. /***************************************************************************\
  840. * InitKeyboardState
  841. *
  842. * This function clears the keyboard down state. It will be required
  843. * when the system resumes from hybernation.
  844. * states.
  845. *
  846. * History:
  847. * 12-12-00 Hiroyama
  848. \***************************************************************************/
  849. VOID InitKeyboardState(
  850. VOID)
  851. {
  852. TAGMSG0(DBGTAG_KBD, "InitKeyboardState >>>>>");
  853. /*
  854. * Clear the cached modifier state for the hotkey.
  855. * (WindowsBug #252051)
  856. */
  857. ClearCachedHotkeyModifiers();
  858. TAGMSG0(DBGTAG_KBD, "InitKeyboardState <<<<<<");
  859. }
  860. /***************************************************************************\
  861. * InitKeyboard
  862. *
  863. * This function gets information about the keyboard and initialize the internal
  864. * states.
  865. *
  866. * History:
  867. * 11-26-90 DavidPe Created.
  868. * XX-XX-00 Hiroyama
  869. \***************************************************************************/
  870. VOID InitKeyboard(VOID)
  871. {
  872. if (!IsRemoteConnection()) {
  873. /*
  874. * Get the BIOS Numlock status.
  875. */
  876. GetBiosNumLockStatus();
  877. /*
  878. * Initialize the keyboard state.
  879. */
  880. InitKeyboardState();
  881. }
  882. UpdatePerUserKeyboardMappings(NULL);
  883. }
  884. VOID UpdatePerUserKeyboardMappings(PUNICODE_STRING pProfileUserName)
  885. {
  886. /*
  887. * Get or clean the Scancode Mapping, if any.
  888. */
  889. InitScancodeMap(pProfileUserName);
  890. }
  891. HKL GetActiveHKL()
  892. {
  893. CheckCritIn();
  894. if (gpqForeground && gpqForeground->spwndActive) {
  895. PTHREADINFO ptiForeground = GETPTI(gpqForeground->spwndActive);
  896. if (ptiForeground && ptiForeground->spklActive) {
  897. return ptiForeground->spklActive->hkl;
  898. }
  899. }
  900. return _GetKeyboardLayout(0L);
  901. }
  902. VOID FinalizeKoreanImeCompStrOnMouseClick(PWND pwnd)
  903. {
  904. PTHREADINFO ptiWnd = GETPTI(pwnd);
  905. /*
  906. * 274007: MFC flushes mouse related messages if keyup is posted
  907. * while it's in context help mode.
  908. */
  909. if (gpqForeground->spwndCapture == NULL &&
  910. /*
  911. * Hack for OnScreen Keyboard: no finalization on button event.
  912. */
  913. (GetAppImeCompatFlags(ptiWnd) & IMECOMPAT_NOFINALIZECOMPSTR) == 0) {
  914. if (LOWORD(ptiWnd->dwExpWinVer) > VER40) {
  915. PWND pwndIme = ptiWnd->spwndDefaultIme;
  916. if (pwndIme && !TestWF(pwndIme, WFINDESTROY)) {
  917. /*
  918. * For new applications, we no longer post hacky WM_KEYUP.
  919. * Instead, we use private IME_SYSTEM message.
  920. */
  921. _PostMessage(pwndIme, WM_IME_SYSTEM, IMS_FINALIZE_COMPSTR, 0);
  922. }
  923. } else {
  924. /*
  925. * For the backward compatibility w/NT4, we post WM_KEYUP to finalize
  926. * the composition string.
  927. */
  928. PostInputMessage(gpqForeground, NULL, WM_KEYUP, VK_PROCESSKEY, 0, 0, 0);
  929. }
  930. }
  931. }
  932. #ifdef GENERIC_INPUT
  933. #ifdef GI_SINK
  934. __inline VOID FillRawMouseInput(
  935. PHIDDATA pHidData,
  936. PMOUSE_INPUT_DATA pmei)
  937. {
  938. /*
  939. * Set the data.
  940. */
  941. pHidData->rid.data.mouse.usFlags = pmei->Flags;
  942. pHidData->rid.data.mouse.ulButtons = pmei->Buttons;
  943. pHidData->rid.data.mouse.ulRawButtons = pmei->RawButtons;
  944. pHidData->rid.data.mouse.lLastX = pmei->LastX;
  945. pHidData->rid.data.mouse.lLastY = pmei->LastY;
  946. pHidData->rid.data.mouse.ulExtraInformation = pmei->ExtraInformation;
  947. }
  948. BOOL PostRawMouseInput(
  949. PQ pq,
  950. DWORD dwTime,
  951. HANDLE hDevice,
  952. PMOUSE_INPUT_DATA pmei)
  953. {
  954. PHIDDATA pHidData;
  955. PWND pwnd;
  956. PPROCESS_HID_TABLE pHidTable;
  957. if (pmei->UnitId == INVALID_UNIT_ID) {
  958. TAGMSG1(DBGTAG_PNP, "PostRawMouseInput: MOUSE_INPUT_DATA %p is already handled.", pmei);
  959. return TRUE;
  960. }
  961. if (pq) {
  962. pHidTable = PtiMouseFromQ(pq)->ppi->pHidTable;
  963. } else {
  964. pHidTable = NULL;
  965. }
  966. if (pHidTable && pHidTable->fRawMouse) {
  967. UserAssert(PtiMouseFromQ(pq)->ppi->pHidTable);
  968. pwnd = PtiMouseFromQ(pq)->ppi->pHidTable->spwndTargetMouse;
  969. if (pwnd) {
  970. pq = GETPTI(pwnd)->pq;
  971. }
  972. pHidData = AllocateHidData(hDevice, RIM_TYPEMOUSE, sizeof(RAWMOUSE), RIM_INPUT, pwnd);
  973. UserAssert(pq);
  974. if (pHidData == NULL) {
  975. // failed to allocate
  976. RIPMSG0(RIP_WARNING, "PostRawMouseInput: filed to allocate HIDDATA.");
  977. return FALSE;
  978. }
  979. UserAssert(pmei);
  980. FillRawMouseInput(pHidData, pmei);
  981. PostInputMessage(pq, pwnd, WM_INPUT, RIM_INPUT, (LPARAM)PtoH(pHidData), dwTime, pmei->ExtraInformation);
  982. }
  983. #if DBG
  984. pHidData = NULL;
  985. #endif
  986. if (IsMouseSinkPresent()) {
  987. /*
  988. * Walk through the global sink list.
  989. */
  990. PLIST_ENTRY pList = gHidRequestTable.ProcessRequestList.Flink;
  991. for (; pList != &gHidRequestTable.ProcessRequestList; pList = pList->Flink) {
  992. PPROCESS_HID_TABLE pProcessHidTable = CONTAINING_RECORD(pList, PROCESS_HID_TABLE, link);
  993. PPROCESSINFO ppiForeground;
  994. if (pq) {
  995. ppiForeground = PtiMouseFromQ(pq)->ppi;
  996. } else {
  997. ppiForeground = NULL;
  998. }
  999. UserAssert(pProcessHidTable);
  1000. if (pProcessHidTable->fRawMouseSink) {
  1001. /*
  1002. * Sink is specified. Let's check out if it's the legid receiver.
  1003. */
  1004. UserAssert(pProcessHidTable->spwndTargetMouse); // shouldn't be NULL.
  1005. if (pProcessHidTable->spwndTargetMouse == NULL ||
  1006. TestWF(pProcessHidTable->spwndTargetMouse, WFINDESTROY) ||
  1007. TestWF(pProcessHidTable->spwndTargetMouse, WFDESTROYED)) {
  1008. /*
  1009. * This guy doesn't have a legit spwndTarget or the window is
  1010. * halfly destroyed.
  1011. */
  1012. #ifdef LATER
  1013. pProcessHidTable->fRawMouse = pProcessHidTable->fRawMouseSink =
  1014. pProcessHidTable->fNoLegacyMouse = FALSE;
  1015. #endif
  1016. continue;
  1017. }
  1018. if (pProcessHidTable->spwndTargetMouse->head.rpdesk != grpdeskRitInput) {
  1019. /*
  1020. * This guy belongs to the other desktop, let's skip it.
  1021. */
  1022. continue;
  1023. }
  1024. if (GETPTI(pProcessHidTable->spwndTargetMouse)->ppi == ppiForeground) {
  1025. /*
  1026. * Should be already handled, let's skip it.
  1027. */
  1028. continue;
  1029. }
  1030. /*
  1031. * Let's post the message to this guy.
  1032. */
  1033. pHidData = AllocateHidData(hDevice, RIM_TYPEMOUSE, sizeof(RAWMOUSE), RIM_INPUTSINK, pProcessHidTable->spwndTargetMouse);
  1034. if (pHidData == NULL) {
  1035. RIPMSG1(RIP_WARNING, "PostInputMessage: failed to allocate HIDDATA for sink: %p", pProcessHidTable);
  1036. return FALSE;
  1037. }
  1038. FillRawMouseInput(pHidData, pmei);
  1039. pwnd = pProcessHidTable->spwndTargetMouse;
  1040. PostInputMessage(GETPTI(pwnd)->pq,
  1041. pwnd,
  1042. WM_INPUT,
  1043. RIM_INPUTSINK,
  1044. (LPARAM)PtoH(pHidData),
  1045. dwTime,
  1046. pmei->ExtraInformation);
  1047. }
  1048. }
  1049. }
  1050. /*
  1051. * Mark this raw input as processed.
  1052. */
  1053. pmei->UnitId = INVALID_UNIT_ID;
  1054. return TRUE;
  1055. }
  1056. #else // GI_SINK
  1057. // original code
  1058. BOOL PostRawMouseInput(
  1059. PQ pq,
  1060. DWORD dwTime,
  1061. HANDLE hDevice,
  1062. PMOUSE_INPUT_DATA pmei)
  1063. {
  1064. PHIDDATA pHidData;
  1065. PWND pwnd;
  1066. UserAssert(PtiMouseFromQ(pq)->ppi->pHidTable);
  1067. if (pmei->UnitId == INVALID_UNIT_ID) {
  1068. TAGMSG1(DBGTAG_PNP, "PostRawMouseInput: MOUSE_INPUT_DATA %p is already handled.", pmei);
  1069. return TRUE;
  1070. }
  1071. pwnd = PtiMouseFromQ(pq)->ppi->pHidTable->spwndTargetMouse;
  1072. if (pwnd) {
  1073. pq = GETPTI(pwnd)->pq;
  1074. }
  1075. pHidData = AllocateHidData(hDevice, RIM_TYPEMOUSE, sizeof(RAWMOUSE), RIM_INPUT, pwnd);
  1076. UserAssert(pq);
  1077. if (pHidData == NULL) {
  1078. // failed to allocate
  1079. RIPMSG0(RIP_WARNING, "PostRawMouseInput: filed to allocate HIDDATA.");
  1080. return FALSE;
  1081. }
  1082. UserAssert(hDevice);
  1083. UserAssert(pmei);
  1084. pHidData->rid.data.mouse.usFlags = pmei->Flags;
  1085. pHidData->rid.data.mouse.ulButtons = pmei->Buttons;
  1086. pHidData->rid.data.mouse.ulRawButtons = pmei->RawButtons;
  1087. pHidData->rid.data.mouse.lLastX = pmei->LastX;
  1088. pHidData->rid.data.mouse.lLastY = pmei->LastY;
  1089. pHidData->rid.data.mouse.ulExtraInformation = pmei->ExtraInformation;
  1090. /*
  1091. * Mark this raw input as processed.
  1092. */
  1093. pmei->UnitId = INVALID_UNIT_ID;
  1094. PostInputMessage(pq, pwnd, WM_INPUT, RIM_INPUT, (LPARAM)PtoH(pHidData), dwTime, pmei->ExtraInformation);
  1095. return TRUE;
  1096. }
  1097. #endif // GI_SINK
  1098. BOOL RawInputRequestedForMouse(PTHREADINFO pti)
  1099. {
  1100. #ifdef GI_SINK
  1101. return gHidCounters.cMouseSinks > 0 || TestRawInputMode(pti, RawMouse);
  1102. #else
  1103. return TestRawInputMode(pti, RawKeyboard);
  1104. #endif
  1105. }
  1106. #endif // GENERIC_INPUT
  1107. /***************************************************************************\
  1108. * xxxButtonEvent (RIT)
  1109. *
  1110. * Button events from the mouse driver go here. Based on the location of
  1111. * the cursor the event is directed to specific window. When a button down
  1112. * occurs, a mouse owner window is established. All mouse events up to and
  1113. * including the corresponding button up go to the mouse owner window. This
  1114. * is done to best simulate what applications want when doing mouse capturing.
  1115. * Since we're processing these events asynchronously, but the application
  1116. * calls SetCapture() in response to it's synchronized processing of input
  1117. * we have no other way to get this functionality.
  1118. *
  1119. * The async keystate table for VK_*BUTTON is updated here.
  1120. *
  1121. * History:
  1122. * 10-18-90 DavidPe Created.
  1123. * 01-25-91 IanJa xxxWindowHitTest change
  1124. * 03-12-92 JonPa Make caller enter crit instead of this function
  1125. \***************************************************************************/
  1126. VOID xxxButtonEvent(
  1127. DWORD ButtonNumber,
  1128. POINT ptPointer,
  1129. BOOL fBreak,
  1130. DWORD time,
  1131. ULONG_PTR ExtraInfo,
  1132. #ifdef GENERIC_INPUT
  1133. HANDLE hDevice,
  1134. PMOUSE_INPUT_DATA pmei,
  1135. #endif
  1136. BOOL bInjected,
  1137. BOOL fDblClk)
  1138. {
  1139. UINT message, usVK, usOtherVK, wHardwareButton;
  1140. PWND pwnd;
  1141. LPARAM lParam;
  1142. WPARAM wParam;
  1143. int xbutton;
  1144. TL tlpwnd;
  1145. PHOOK pHook;
  1146. #ifdef GENERIC_INPUT
  1147. BOOL fMouseExclusive = FALSE;
  1148. #endif
  1149. #ifdef REDIRECTION
  1150. PWND pwndStart;
  1151. #endif // REDIRECTION
  1152. CheckCritIn();
  1153. /*
  1154. * Cancel Alt-Tab if the user presses a mouse button
  1155. */
  1156. if (gspwndAltTab != NULL) {
  1157. xxxCancelCoolSwitch();
  1158. }
  1159. /*
  1160. * Grab the mouse button before we process any button swapping.
  1161. * This is so we won't get confused if someone calls
  1162. * SwapMouseButtons() inside a down-click/up-click.
  1163. */
  1164. wHardwareButton = (UINT)ButtonNumber;
  1165. /*
  1166. * If this is the left or right mouse button, we have to handle mouse
  1167. * button swapping.
  1168. */
  1169. if (ButtonNumber & (MOUSE_BUTTON_LEFT | MOUSE_BUTTON_RIGHT)) {
  1170. /*
  1171. * If button swapping is on, swap the mouse buttons
  1172. */
  1173. if (SYSMET(SWAPBUTTON)) {
  1174. ButtonNumber ^= (MOUSE_BUTTON_LEFT | MOUSE_BUTTON_RIGHT);
  1175. }
  1176. /*
  1177. * Figure out VK
  1178. */
  1179. if (ButtonNumber == MOUSE_BUTTON_RIGHT) {
  1180. usVK = VK_RBUTTON;
  1181. usOtherVK = VK_LBUTTON;
  1182. } else if (ButtonNumber == MOUSE_BUTTON_LEFT) {
  1183. usVK = VK_LBUTTON;
  1184. usOtherVK = VK_RBUTTON;
  1185. } else {
  1186. RIPMSG1(RIP_ERROR, "Unexpected Button number %d", ButtonNumber);
  1187. }
  1188. /*
  1189. * If the mouse buttons have recently been swapped AND the button
  1190. * transition doesn't match what we have in our keystate, then swap the
  1191. * button to match.
  1192. * This is to fix the ruler (tabs and margins) in Word 97 SR1, which
  1193. * calls SwapMouseButtons(0) to determine if button swapping is on, and
  1194. * if so then calls SwapMouseButtons(1) to restore it: if we receive a
  1195. * button event between these two calls, we may swap incorrectly, and
  1196. * be left with a mouse button stuck down or see the wrong button going
  1197. * down. This really messed up single/double button tab/margin setting!
  1198. * The same bug shows up under Windows '95, although very infrequently:
  1199. * Word 9 will use GetSystemMetrics(SM_SWAPBUTTON) instead according to
  1200. * to Mark Walker (MarkWal). (IanJa) #165157
  1201. */
  1202. if (gbMouseButtonsRecentlySwapped) {
  1203. if ((!fBreak == !!TestAsyncKeyStateDown(usVK)) &&
  1204. (fBreak == !!TestAsyncKeyStateDown(usOtherVK))) {
  1205. RIPMSG4(RIP_WARNING, "Correct %s %s to %s %s",
  1206. ButtonNumber == MOUSE_BUTTON_LEFT ? "Left" : "Right",
  1207. fBreak ? "Up" : "Down",
  1208. ButtonNumber == MOUSE_BUTTON_LEFT ? "Right" : "Left",
  1209. fBreak ? "Up" : "Down");
  1210. ButtonNumber ^= (MOUSE_BUTTON_LEFT | MOUSE_BUTTON_RIGHT);
  1211. usVK = usOtherVK;
  1212. }
  1213. gbMouseButtonsRecentlySwapped = FALSE;
  1214. }
  1215. }
  1216. xbutton = 0;
  1217. switch (ButtonNumber) {
  1218. case MOUSE_BUTTON_RIGHT:
  1219. if (fBreak) {
  1220. message = WM_RBUTTONUP;
  1221. } else {
  1222. if (ISTS() && fDblClk)
  1223. message = WM_RBUTTONDBLCLK;
  1224. else
  1225. message = WM_RBUTTONDOWN;
  1226. }
  1227. break;
  1228. case MOUSE_BUTTON_LEFT:
  1229. if (fBreak) {
  1230. message = WM_LBUTTONUP;
  1231. } else {
  1232. if (ISTS() && fDblClk)
  1233. message = WM_LBUTTONDBLCLK;
  1234. else
  1235. message = WM_LBUTTONDOWN;
  1236. }
  1237. break;
  1238. case MOUSE_BUTTON_MIDDLE:
  1239. if (fBreak) {
  1240. message = WM_MBUTTONUP;
  1241. } else {
  1242. if (ISTS() && fDblClk)
  1243. message = WM_MBUTTONDBLCLK;
  1244. else
  1245. message = WM_MBUTTONDOWN;
  1246. }
  1247. usVK = VK_MBUTTON;
  1248. break;
  1249. case MOUSE_BUTTON_X1:
  1250. case MOUSE_BUTTON_X2:
  1251. if (fBreak) {
  1252. message = WM_XBUTTONUP;
  1253. } else {
  1254. if (ISTS() && fDblClk)
  1255. message = WM_XBUTTONDBLCLK;
  1256. else
  1257. message = WM_XBUTTONDOWN;
  1258. }
  1259. if (ButtonNumber == MOUSE_BUTTON_X1) {
  1260. usVK = VK_XBUTTON1;
  1261. xbutton = XBUTTON1;
  1262. } else {
  1263. usVK = VK_XBUTTON2;
  1264. xbutton = XBUTTON2;
  1265. }
  1266. break;
  1267. default:
  1268. /*
  1269. * Unknown button. Since we don't
  1270. * have messages for these buttons, ignore them.
  1271. */
  1272. return;
  1273. }
  1274. UserAssert(usVK != 0);
  1275. /*
  1276. * Check for click-lock
  1277. */
  1278. if (TestEffectUP(MOUSECLICKLOCK)) {
  1279. if (message == WM_LBUTTONDOWN) {
  1280. if (gfStartClickLock) {
  1281. /*
  1282. * Already inside click-lock, so just throw this message away
  1283. * and turn click-lock off.
  1284. */
  1285. gfStartClickLock = FALSE;
  1286. return;
  1287. } else {
  1288. /*
  1289. * Start click-lock and record the time.
  1290. */
  1291. gfStartClickLock = TRUE;
  1292. gdwStartClickLockTick = time;
  1293. }
  1294. } else if (message == WM_LBUTTONUP) {
  1295. if (gfStartClickLock) {
  1296. DWORD dwDeltaTick = time - gdwStartClickLockTick;
  1297. if (dwDeltaTick > UPDWORDValue(SPI_GETMOUSECLICKLOCKTIME)) {
  1298. /*
  1299. * Inside a potential click-lock, so throw this message away
  1300. * if waited beyond the click-lock period.
  1301. */
  1302. return;
  1303. } else {
  1304. /*
  1305. * The mouse up occurred before the click-lock period completed,
  1306. * so cancel the click-lock.
  1307. */
  1308. gfStartClickLock = FALSE;
  1309. }
  1310. }
  1311. }
  1312. }
  1313. wParam = MAKEWPARAM(0, xbutton);
  1314. /*
  1315. * Call low level mouse hooks to see if they allow this message
  1316. * to pass through USER
  1317. */
  1318. if ((pHook = PhkFirstValid(PtiCurrent(), WH_MOUSE_LL)) != NULL) {
  1319. MSLLHOOKSTRUCT mslls;
  1320. BOOL bAnsiHook;
  1321. mslls.pt = ptPointer;
  1322. mslls.mouseData = (LONG)wParam;
  1323. mslls.flags = bInjected;
  1324. mslls.time = time;
  1325. mslls.dwExtraInfo = ExtraInfo;
  1326. if (xxxCallHook2(pHook, HC_ACTION, (DWORD)message, (LPARAM)&mslls, &bAnsiHook)) {
  1327. return;
  1328. }
  1329. }
  1330. #ifdef GENERIC_INPUT
  1331. UserAssert(gpqForeground == NULL || PtiMouseFromQ(gpqForeground));
  1332. if (gpqForeground) {
  1333. if (hDevice && RawInputRequestedForMouse(PtiMouseFromQ(gpqForeground))) {
  1334. PostRawMouseInput(gpqForeground, time, hDevice, pmei);
  1335. }
  1336. }
  1337. #endif
  1338. /*
  1339. * This is from HYDRA
  1340. */
  1341. UserAssert(grpdeskRitInput != NULL);
  1342. #ifdef GENERIC_INPUT
  1343. if (gpqForeground && TestRawInputMode(PtiMouseFromQ(gpqForeground), CaptureMouse)) {
  1344. fMouseExclusive = TRUE;
  1345. pwnd = PtiMouseFromQ(gpqForeground)->ppi->pHidTable->spwndTargetMouse;
  1346. UserAssert(pwnd);
  1347. if (pwnd) {
  1348. goto KeyStatusUpdate;
  1349. }
  1350. // Something bad happened to our HidTable, but
  1351. // not let it AV because of that.
  1352. }
  1353. #endif
  1354. #ifdef REDIRECTION
  1355. /*
  1356. * Call the speed hit test hook
  1357. */
  1358. pwndStart = xxxCallSpeedHitTestHook(&ptPointer);
  1359. if (pwndStart == NULL) {
  1360. pwndStart = grpdeskRitInput->pDeskInfo->spwnd;
  1361. }
  1362. pwnd = SpeedHitTest(pwndStart, ptPointer);
  1363. #else
  1364. pwnd = SpeedHitTest(grpdeskRitInput->pDeskInfo->spwnd, ptPointer);
  1365. #endif // REDIRECTION
  1366. /*
  1367. * Only post the message if we actually hit a window.
  1368. */
  1369. if (pwnd == NULL) {
  1370. return;
  1371. }
  1372. /*
  1373. * Assign the message to a window.
  1374. */
  1375. lParam = MAKELONG((SHORT)ptPointer.x, (SHORT)ptPointer.y);
  1376. /*
  1377. * KOREAN:
  1378. * Send VK_PROCESSKEY to finalize current composition string (NT4 behavior)
  1379. * Post private message to let IMM finalize the composition string (NT5)
  1380. */
  1381. if (IS_IME_ENABLED() &&
  1382. !fBreak &&
  1383. KOREAN_KBD_LAYOUT(GetActiveHKL()) &&
  1384. !TestCF(pwnd, CFIME) &&
  1385. gpqForeground != NULL) {
  1386. FinalizeKoreanImeCompStrOnMouseClick(pwnd);
  1387. }
  1388. /*
  1389. * If screen capture is active do it
  1390. */
  1391. if (gspwndScreenCapture != NULL)
  1392. pwnd = gspwndScreenCapture;
  1393. /*
  1394. * If this is a button down event and there isn't already
  1395. * a mouse owner, setup the mouse ownership globals.
  1396. */
  1397. if (gspwndMouseOwner == NULL) {
  1398. if (!fBreak) {
  1399. PWND pwndCapture;
  1400. /*
  1401. * BIG HACK: If the foreground window has the capture
  1402. * and the mouse is outside the foreground queue then
  1403. * send a buttondown/up pair to that queue so it'll
  1404. * cancel it's modal loop.
  1405. */
  1406. if (pwndCapture = PwndForegroundCapture()) {
  1407. if (GETPTI(pwnd)->pq != GETPTI(pwndCapture)->pq) {
  1408. PQ pqCapture;
  1409. pqCapture = GETPTI(pwndCapture)->pq;
  1410. PostInputMessage(pqCapture, pwndCapture, message,
  1411. 0, lParam, 0, 0);
  1412. PostInputMessage(pqCapture, pwndCapture, message + 1,
  1413. 0, lParam, 0, 0);
  1414. /*
  1415. * EVEN BIGGER HACK: To maintain compatibility
  1416. * with how tracking deals with this, we don't
  1417. * pass this event along. This prevents mouse
  1418. * clicks in other windows from causing them to
  1419. * become foreground while tracking. The exception
  1420. * to this is when we have the sysmenu up on
  1421. * an iconic window.
  1422. */
  1423. if ((GETPTI(pwndCapture)->pmsd != NULL) &&
  1424. !IsMenuStarted(GETPTI(pwndCapture))) {
  1425. return;
  1426. }
  1427. }
  1428. }
  1429. Lock(&(gspwndMouseOwner), pwnd);
  1430. gwMouseOwnerButton |= wHardwareButton;
  1431. glinp.ptLastClick = gpsi->ptCursor;
  1432. } else {
  1433. /*
  1434. * The mouse owner must have been destroyed or unlocked
  1435. * by a fullscreen switch. Keep the button state in sync.
  1436. */
  1437. gwMouseOwnerButton &= ~wHardwareButton;
  1438. }
  1439. } else {
  1440. /*
  1441. * Give any other button events to the mouse-owner window
  1442. * to be consistent with old capture semantics.
  1443. */
  1444. if (gspwndScreenCapture == NULL) {
  1445. /*
  1446. * NT5 Foreground and Drag Drop.
  1447. * If the mouse goes up on a different thread
  1448. * make the mouse up thread the owner of this click
  1449. */
  1450. if (fBreak && (GETPTI(pwnd) != GETPTI(gspwndMouseOwner))) {
  1451. glinp.ptiLastWoken = GETPTI(pwnd);
  1452. TAGMSG1(DBGTAG_FOREGROUND, "xxxButtonEvent. ptiLastWoken %#p", glinp.ptiLastWoken);
  1453. }
  1454. pwnd = gspwndMouseOwner;
  1455. }
  1456. /*
  1457. * If this is the button-up event for the mouse-owner
  1458. * clear gspwndMouseOwner.
  1459. */
  1460. if (fBreak) {
  1461. gwMouseOwnerButton &= ~wHardwareButton;
  1462. if (!gwMouseOwnerButton)
  1463. Unlock(&gspwndMouseOwner);
  1464. } else {
  1465. gwMouseOwnerButton |= wHardwareButton;
  1466. }
  1467. }
  1468. KeyStatusUpdate:
  1469. /*
  1470. * Only update the async keystate when we know which window this
  1471. * event goes to (or else we can't keep the thread specific key
  1472. * state in sync).
  1473. */
  1474. UserAssert(usVK != 0);
  1475. UpdateAsyncKeyState(GETPTI(pwnd)->pq, usVK, fBreak);
  1476. #ifdef GENERIC_INPUT
  1477. if (fMouseExclusive) {
  1478. /*
  1479. * If the foreground application requests mouse exclusive
  1480. * raw input, let's not post the activate messages etc.
  1481. * The mouse exclusiveness requires no activation,
  1482. * even within the same app.
  1483. */
  1484. return;
  1485. }
  1486. #endif
  1487. /*
  1488. * Put pwnd into the foreground if this is a button down event
  1489. * and it isn't already the foreground window.
  1490. */
  1491. if (!fBreak && GETPTI(pwnd)->pq != gpqForeground) {
  1492. /*
  1493. * If this is an WM_*BUTTONDOWN on a desktop window just do
  1494. * cancel-mode processing. Check to make sure that there
  1495. * wasn't already a mouse owner window. See comments below.
  1496. */
  1497. if ((gpqForeground != NULL) && (pwnd == grpdeskRitInput->pDeskInfo->spwnd) &&
  1498. ((gwMouseOwnerButton & wHardwareButton) ||
  1499. (gwMouseOwnerButton == 0))) {
  1500. PostEventMessage(gpqForeground->ptiMouse,
  1501. gpqForeground, QEVENT_CANCELMODE, NULL, 0, 0, 0);
  1502. } else if ((gwMouseOwnerButton & wHardwareButton) ||
  1503. (gwMouseOwnerButton == 0)) {
  1504. /*
  1505. * Don't bother setting the foreground window if there's
  1506. * already mouse owner window from a button-down different
  1507. * than this event. This prevents weird things from happening
  1508. * when the user starts a tracking operation with the left
  1509. * button and clicks the right button during the tracking
  1510. * operation.
  1511. */
  1512. /*
  1513. * If pwnd is a descendent of a WS_EX_NOACTIVATE window, then we
  1514. * won't set it to the foreground
  1515. */
  1516. PWND pwndTopLevel = GetTopLevelWindow(pwnd);
  1517. if (!TestWF(pwndTopLevel, WEFNOACTIVATE)) {
  1518. ThreadLockAlways(pwnd, &tlpwnd);
  1519. xxxSetForegroundWindow2(pwnd, NULL, 0);
  1520. /*
  1521. * Ok to unlock right away: the above didn't really leave the crit sec.
  1522. * We lock here for consistency so the debug macros work ok.
  1523. */
  1524. ThreadUnlock(&tlpwnd);
  1525. }
  1526. }
  1527. }
  1528. #ifdef GENERIC_INPUT
  1529. if (TestRawInputMode(PtiMouseFromQ(GETPTI(pwnd)->pq), NoLegacyMouse)) {
  1530. return;
  1531. }
  1532. #endif
  1533. if (GETPTI(pwnd)->pq->QF_flags & QF_MOUSEMOVED) {
  1534. PostMove(GETPTI(pwnd)->pq);
  1535. }
  1536. PostInputMessage(GETPTI(pwnd)->pq, pwnd, message, wParam, lParam, time, ExtraInfo);
  1537. /*
  1538. * If this is a mouse up event and stickykeys is enabled all latched
  1539. * keys will be released.
  1540. */
  1541. if (fBreak && (TEST_ACCESSFLAG(StickyKeys, SKF_STICKYKEYSON) ||
  1542. TEST_ACCESSFLAG(MouseKeys, MKF_MOUSEKEYSON))) {
  1543. xxxHardwareMouseKeyUp(ButtonNumber);
  1544. }
  1545. if (message == WM_LBUTTONDOWN) {
  1546. PDESKTOP pdesk = GETPTI(pwnd)->rpdesk;
  1547. if (pdesk != NULL && pdesk->rpwinstaParent != NULL) {
  1548. UserAssert(!(pdesk->rpwinstaParent->dwWSF_Flags & WSF_NOIO));
  1549. #ifdef HUNGAPP_GHOSTING
  1550. if (FHungApp(GETPTI(pwnd), CMSHUNGAPPTIMEOUT)) {
  1551. SignalGhost(pwnd);
  1552. }
  1553. #endif // HUNGAPP_GHOSTING
  1554. }
  1555. }
  1556. }
  1557. /***************************************************************************\
  1558. *
  1559. * The Button-Click Queue is protected by the semaphore gcsMouseEventQueue
  1560. *
  1561. \***************************************************************************/
  1562. #ifdef LOCK_MOUSE_CODE
  1563. #pragma alloc_text(MOUSE, QueueMouseEvent)
  1564. #endif
  1565. /***************************************************************************\
  1566. * QueueMouseEvent
  1567. *
  1568. * Params:
  1569. * ButtonFlags - button flags from the driver in MOUSE_INPUT_DATA.ButtonFlags
  1570. *
  1571. * ButtonData - data from the driver in MOUSE_INPUT_DATA.ButtonData
  1572. * Stores the wheel delta
  1573. *
  1574. * ExtraInfo - extra information from the driver in MOUSE_INPUT_DATA.ExtraInfo
  1575. * ptMouse - mouse delta
  1576. * time - tick count at time of event
  1577. * bInjected - injected by SendInput?
  1578. * bWakeRIT - wake the RIT?
  1579. *
  1580. \***************************************************************************/
  1581. VOID QueueMouseEvent(
  1582. USHORT ButtonFlags,
  1583. USHORT ButtonData,
  1584. ULONG_PTR ExtraInfo,
  1585. POINT ptMouse,
  1586. LONG time,
  1587. #ifdef GENERIC_INPUT
  1588. HANDLE hDevice,
  1589. PMOUSE_INPUT_DATA pmei,
  1590. #endif
  1591. BOOL bInjected,
  1592. BOOL bWakeRIT
  1593. )
  1594. {
  1595. CheckCritOut();
  1596. EnterMouseCrit();
  1597. LOGTIME(gMouseQueueMouseEventTime);
  1598. /*
  1599. * Button data must always be accompanied by a flag to interpret it.
  1600. */
  1601. UserAssert(ButtonData == 0 || ButtonFlags != 0);
  1602. /*
  1603. * We can coalesce this mouse event with the previous event if there is a
  1604. * previous event, and if the previous event and this event involve no
  1605. * key transitions.
  1606. */
  1607. if ((gdwMouseEvents == 0) ||
  1608. (ButtonFlags != 0) ||
  1609. (gMouseEventQueue[gdwMouseQueueHead].ButtonFlags != 0)) {
  1610. /*
  1611. * Can't coalesce: must add a new mouse event
  1612. */
  1613. if (gdwMouseEvents >= NELEM_BUTTONQUEUE) {
  1614. /*
  1615. * But no more room!
  1616. */
  1617. LeaveMouseCrit();
  1618. UserBeep(440, 125);
  1619. return;
  1620. }
  1621. gdwMouseQueueHead = (gdwMouseQueueHead + 1) % NELEM_BUTTONQUEUE;
  1622. gMouseEventQueue[gdwMouseQueueHead].ButtonFlags = ButtonFlags;
  1623. gMouseEventQueue[gdwMouseQueueHead].ButtonData = ButtonData;
  1624. gdwMouseEvents++;
  1625. }
  1626. gMouseEventQueue[gdwMouseQueueHead].ExtraInfo = ExtraInfo;
  1627. gMouseEventQueue[gdwMouseQueueHead].ptPointer = ptMouse;
  1628. gMouseEventQueue[gdwMouseQueueHead].time = time;
  1629. gMouseEventQueue[gdwMouseQueueHead].bInjected = bInjected;
  1630. #ifdef GENERIC_INPUT
  1631. gMouseEventQueue[gdwMouseQueueHead].hDevice = hDevice;
  1632. if (pmei) {
  1633. gMouseEventQueue[gdwMouseQueueHead].rawData = *pmei;
  1634. } else {
  1635. /*
  1636. * To indicate the rawData is invalid, set INVALID_UNIT_ID.
  1637. */
  1638. gMouseEventQueue[gdwMouseQueueHead].rawData.UnitId = INVALID_UNIT_ID;
  1639. }
  1640. #endif
  1641. LeaveMouseCrit();
  1642. if (bWakeRIT) {
  1643. /*
  1644. * Signal RIT to complete the mouse input processing
  1645. */
  1646. KeSetEvent(gpkeMouseData, EVENT_INCREMENT, FALSE);
  1647. }
  1648. }
  1649. /*****************************************************************************\
  1650. *
  1651. * Gets mouse events out of the queue
  1652. *
  1653. * Returns:
  1654. * TRUE - a mouse event is obtained in *pme
  1655. * FALSE - no mouse event available
  1656. *
  1657. \*****************************************************************************/
  1658. BOOL UnqueueMouseEvent(
  1659. PMOUSEEVENT pme
  1660. )
  1661. {
  1662. DWORD dwTail;
  1663. EnterMouseCrit();
  1664. LOGTIME(gMouseUnqueueMouseEventTime);
  1665. if (gdwMouseEvents == 0) {
  1666. LeaveMouseCrit();
  1667. return FALSE;
  1668. } else {
  1669. dwTail = (gdwMouseQueueHead - gdwMouseEvents + 1) % NELEM_BUTTONQUEUE;
  1670. *pme = gMouseEventQueue[dwTail];
  1671. gdwMouseEvents--;
  1672. }
  1673. LeaveMouseCrit();
  1674. return TRUE;
  1675. }
  1676. VOID xxxDoButtonEvent(PMOUSEEVENT pme)
  1677. {
  1678. ULONG dwButtonMask;
  1679. ULONG dwButtonState;
  1680. LPARAM lParam;
  1681. BOOL fWheel;
  1682. PHOOK pHook;
  1683. ULONG dwButtonData = (ULONG) pme->ButtonData;
  1684. CheckCritIn();
  1685. dwButtonState = (ULONG) pme->ButtonFlags;
  1686. fWheel = dwButtonState & MOUSE_WHEEL;
  1687. dwButtonState &= ~MOUSE_WHEEL;
  1688. for( dwButtonMask = 1;
  1689. dwButtonState != 0;
  1690. dwButtonData >>= 2, dwButtonState >>= 2, dwButtonMask <<= 1) {
  1691. if (dwButtonState & 1) {
  1692. xxxButtonEvent(dwButtonMask, pme->ptPointer, FALSE,
  1693. pme->time, pme->ExtraInfo,
  1694. #ifdef GENERIC_INPUT
  1695. pme->hDevice,
  1696. &pme->rawData,
  1697. #endif
  1698. pme->bInjected,
  1699. gbClientDoubleClickSupport && (dwButtonData & 1));
  1700. }
  1701. if (dwButtonState & 2) {
  1702. xxxButtonEvent(dwButtonMask, pme->ptPointer, TRUE,
  1703. pme->time, pme->ExtraInfo,
  1704. #ifdef GENERIC_INPUT
  1705. pme->hDevice,
  1706. &pme->rawData,
  1707. #endif
  1708. pme->bInjected ,FALSE);
  1709. }
  1710. }
  1711. /*
  1712. * Handle the wheel msg.
  1713. */
  1714. if (fWheel && pme->ButtonData != 0 && gpqForeground) {
  1715. lParam = MAKELONG((SHORT)pme->ptPointer.x, (SHORT)pme->ptPointer.y);
  1716. /*
  1717. * Call low level mouse hooks to see if they allow this message
  1718. * to pass through USER
  1719. */
  1720. if ((pHook = PhkFirstValid(PtiCurrent(), WH_MOUSE_LL)) != NULL) {
  1721. MSLLHOOKSTRUCT mslls;
  1722. BOOL bAnsiHook;
  1723. mslls.pt = pme->ptPointer;
  1724. mslls.mouseData = MAKELONG(0, pme->ButtonData);
  1725. mslls.flags = pme->bInjected;
  1726. mslls.time = pme->time;
  1727. mslls.dwExtraInfo = pme->ExtraInfo;
  1728. if (xxxCallHook2(pHook, HC_ACTION, (DWORD)WM_MOUSEWHEEL,
  1729. (LPARAM)&mslls, &bAnsiHook)) {
  1730. return;
  1731. }
  1732. }
  1733. #ifdef GENERIC_INPUT
  1734. UserAssert(gpqForeground == NULL || PtiMouseFromQ(gpqForeground));
  1735. if (gpqForeground && RawInputRequestedForMouse(PtiMouseFromQ(gpqForeground))) {
  1736. PostRawMouseInput(gpqForeground, pme->time, pme->hDevice, &pme->rawData);
  1737. }
  1738. if (gpqForeground && !TestRawInputMode(PtiMouseFromQ(gpqForeground), NoLegacyMouse)) {
  1739. #endif
  1740. PostInputMessage(
  1741. gpqForeground,
  1742. NULL,
  1743. WM_MOUSEWHEEL,
  1744. MAKELONG(0, pme->ButtonData),
  1745. lParam, pme->time,
  1746. pme->ExtraInfo);
  1747. #ifdef GENERIC_INPUT
  1748. }
  1749. #endif
  1750. return;
  1751. }
  1752. }
  1753. VOID NTAPI InputApc(
  1754. IN PVOID ApcContext,
  1755. IN PIO_STATUS_BLOCK IoStatusBlock,
  1756. IN ULONG Reserved
  1757. )
  1758. {
  1759. PDEVICEINFO pDeviceInfo = (PDEVICEINFO)ApcContext;
  1760. UNREFERENCED_PARAMETER(Reserved);
  1761. /*
  1762. * Check if the RIT is being terminated.
  1763. * If we hit this assertion, the RIT was killed by someone inadvertently.
  1764. * Not much can be done if it once happens.
  1765. */
  1766. UserAssert(gptiRit);
  1767. UserAssert((gptiRit->TIF_flags & TIF_INCLEANUP) == 0);
  1768. #ifdef DIAGNOSE_IO
  1769. pDeviceInfo->nReadsOutstanding--;
  1770. #endif
  1771. /*
  1772. * If this device needs freeing, abandon reading now and request the free.
  1773. * (Don't even process the input that we received in this APC)
  1774. */
  1775. if (pDeviceInfo->usActions & GDIAF_FREEME) {
  1776. #ifdef GENERIC_INPUT
  1777. CheckCritOut();
  1778. EnterCrit();
  1779. #endif
  1780. EnterDeviceInfoListCrit();
  1781. pDeviceInfo->bFlags &= ~GDIF_READING;
  1782. FreeDeviceInfo(pDeviceInfo);
  1783. LeaveDeviceInfoListCrit();
  1784. #ifdef GENERIC_INPUT
  1785. LeaveCrit();
  1786. #endif
  1787. return;
  1788. }
  1789. if (NT_SUCCESS(IoStatusBlock->Status) && pDeviceInfo->handle) {
  1790. PDEVICE_TEMPLATE pDevTpl = &aDeviceTemplate[pDeviceInfo->type];
  1791. pDevTpl->DeviceRead(pDeviceInfo);
  1792. }
  1793. if (IsRemoteConnection()) {
  1794. PoSetSystemState(ES_SYSTEM_REQUIRED);
  1795. }
  1796. StartDeviceRead(pDeviceInfo);
  1797. }
  1798. /***************************************************************************\
  1799. * ProcessMouseInput
  1800. *
  1801. * This function is called whenever a mouse event occurs. Once the event
  1802. * has been processed by USER, StartDeviceRead() is called again to request
  1803. * the next mouse event.
  1804. *
  1805. * When this routin returns, InputApc will start another read.
  1806. *
  1807. * History:
  1808. * 11-26-90 DavidPe Created.
  1809. * 07-23-92 Mikehar Moved most of the processing to _InternalMouseEvent()
  1810. * 11-08-92 JonPa Rewrote button code to work with new mouse drivers
  1811. * 11-18-97 IanJa Renamed from MouseApcProcedure etc, for multiple mice
  1812. \***************************************************************************/
  1813. VOID ProcessMouseInput(
  1814. PDEVICEINFO pMouseInfo)
  1815. {
  1816. PMOUSE_INPUT_DATA pmei, pmeiNext;
  1817. LONG time;
  1818. POINT ptLastMove;
  1819. /*
  1820. * This is an APC, so we don't need the DeviceInfoList Critical Section
  1821. * In fact, we don't want it either. We will not remove the device until
  1822. * ProcessMouseInput has signalled that it is OK to do so. (TBD)
  1823. */
  1824. CheckCritOut();
  1825. CheckDeviceInfoListCritOut();
  1826. UserAssert(pMouseInfo);
  1827. UserAssert((PtiCurrentShared() == gTermIO.ptiDesktop) ||
  1828. (PtiCurrentShared() == gTermNOIO.ptiDesktop));
  1829. LOGTIME(gMouseProcessMiceInputTime);
  1830. if (gptiBlockInput != NULL) {
  1831. return;
  1832. }
  1833. if (TEST_ACCF(ACCF_ACCESSENABLED)) {
  1834. /*
  1835. * Any mouse movement resets the count of consecutive shift key
  1836. * presses. The shift key is used to enable & disable the
  1837. * stickykeys accessibility functionality.
  1838. */
  1839. gStickyKeysLeftShiftCount = 0;
  1840. gStickyKeysRightShiftCount = 0;
  1841. /*
  1842. * Any mouse movement also cancels the FilterKeys activation timer.
  1843. * Entering critsect here breaks non-jerky mouse movement
  1844. */
  1845. if (gtmridFKActivation != 0) {
  1846. EnterCrit();
  1847. KILLRITTIMER(NULL, gtmridFKActivation);
  1848. gtmridFKActivation = 0;
  1849. gFilterKeysState = FKMOUSEMOVE;
  1850. LeaveCrit();
  1851. }
  1852. }
  1853. #ifdef MOUSE_IP
  1854. /*
  1855. * Any mouse movement stops the sonar.
  1856. */
  1857. if (IS_SONAR_ACTIVE()) {
  1858. EnterCrit();
  1859. if (IS_SONAR_ACTIVE()) {
  1860. StopSonar();
  1861. CLEAR_SONAR_LASTVK();
  1862. }
  1863. LeaveCrit();
  1864. }
  1865. #endif
  1866. if (!NT_SUCCESS(pMouseInfo->iosb.Status)) {
  1867. /*
  1868. * If we get a bad status, we abandon reading this mouse.
  1869. */
  1870. if (!IsRemoteConnection())
  1871. if (pMouseInfo->iosb.Status != STATUS_DELETE_PENDING) {
  1872. RIPMSG3(RIP_ERROR, "iosb.Status %lx for mouse %#p (id %x) tell IanJa x63321",
  1873. pMouseInfo->iosb.Status,
  1874. pMouseInfo, pMouseInfo->mouse.Attr.MouseIdentifier);
  1875. }
  1876. return;
  1877. }
  1878. /*
  1879. * get the last move point from ptCursorAsync
  1880. */
  1881. ptLastMove = gptCursorAsync;
  1882. pmei = pMouseInfo->mouse.Data;
  1883. while (pmei != NULL) {
  1884. time = NtGetTickCount();
  1885. /*
  1886. * Figure out where the next event is.
  1887. */
  1888. pmeiNext = pmei + 1;
  1889. if ((PUCHAR)pmeiNext >=
  1890. (PUCHAR)(((PUCHAR)pMouseInfo->mouse.Data) + pMouseInfo->iosb.Information)) {
  1891. /*
  1892. * If there isn't another event set pmeiNext to
  1893. * NULL so we exit the loop and don't get confused.
  1894. */
  1895. pmeiNext = NULL;
  1896. }
  1897. /*
  1898. * If a PS/2 mouse was plugged in, evaluate the (new) mouse and
  1899. * the skip the input record.
  1900. */
  1901. if (pmei->Flags & MOUSE_ATTRIBUTES_CHANGED) {
  1902. RequestDeviceChange(pMouseInfo, GDIAF_REFRESH_MOUSE, FALSE);
  1903. goto NextMouseInputRecord;
  1904. }
  1905. /*
  1906. * First process any mouse movement that occured.
  1907. * It is important to process movement before button events, otherwise
  1908. * absolute coordinate pointing devices like touch-screens and tablets
  1909. * will produce button clicks at old coordinates.
  1910. */
  1911. if (pmei->LastX || pmei->LastY) {
  1912. /*
  1913. * Get the actual point that will be injected.
  1914. */
  1915. GetMouseCoord(pmei->LastX,
  1916. pmei->LastY,
  1917. pmei->Flags,
  1918. time,
  1919. pmei->ExtraInformation,
  1920. &ptLastMove);
  1921. /*
  1922. * If this is a move-only event, and the next one is also a
  1923. * move-only event, skip/coalesce it.
  1924. */
  1925. if ( (pmeiNext != NULL) &&
  1926. (pmei->ButtonFlags == 0) &&
  1927. (pmeiNext->ButtonFlags == 0) &&
  1928. (fAbsoluteMouse(pmei) == fAbsoluteMouse(pmeiNext))) {
  1929. pmei = pmeiNext;
  1930. continue;
  1931. }
  1932. #ifdef GENERIC_INPUT
  1933. UserAssert(sizeof(HANDLE) == sizeof(pMouseInfo));
  1934. #endif
  1935. /*
  1936. * Moves the cursor on the screen and updates gptCursorAsync
  1937. * Call directly xxxMoveEventAbsolute because we already did the
  1938. * acceleration sensitivity and clipping.
  1939. */
  1940. xxxMoveEventAbsolute(
  1941. ptLastMove.x,
  1942. ptLastMove.y,
  1943. pmei->ExtraInformation,
  1944. #ifdef GENERIC_INPUT
  1945. PtoHq(pMouseInfo),
  1946. pmei,
  1947. #endif
  1948. time,
  1949. FALSE
  1950. );
  1951. /*
  1952. * Now update ptLastMove with ptCursorAsync because ptLastMove
  1953. * doesn't reflect the clipping.
  1954. */
  1955. ptLastMove = gptCursorAsync;
  1956. }
  1957. /*
  1958. * Queue mouse event for the other thread to pick up when it finishes
  1959. * with the USER critical section.
  1960. * If pmeiNext == NULL, there is no more mouse input yet, so wake RIT.
  1961. */
  1962. QueueMouseEvent(
  1963. pmei->ButtonFlags,
  1964. pmei->ButtonData,
  1965. pmei->ExtraInformation,
  1966. gptCursorAsync,
  1967. time,
  1968. #ifdef GENERIC_INPUT
  1969. PtoH(pMouseInfo),
  1970. pmei,
  1971. #endif
  1972. FALSE,
  1973. (pmeiNext == NULL));
  1974. NextMouseInputRecord:
  1975. pmei = pmeiNext;
  1976. }
  1977. }
  1978. /***************************************************************************\
  1979. * IsHexNumpadKeys (RIT) inline
  1980. *
  1981. * If you change this code, you may need to change
  1982. * xxxInternalToUnicode() as well.
  1983. \***************************************************************************/
  1984. __inline BOOL IsHexNumpadKeys(
  1985. BYTE Vk,
  1986. WORD wScanCode)
  1987. {
  1988. return (wScanCode >= SCANCODE_NUMPAD_FIRST && wScanCode <= SCANCODE_NUMPAD_LAST && aVkNumpad[wScanCode - SCANCODE_NUMPAD_FIRST] != 0xff) ||
  1989. (Vk >= L'A' && Vk <= L'F') ||
  1990. (Vk >= L'0' && Vk <= L'9');
  1991. }
  1992. /***************************************************************************\
  1993. * LowLevelHexNumpad (RIT) inline
  1994. *
  1995. * If you change this code, you may need to change
  1996. * xxxInternalToUnicode() as well.
  1997. \***************************************************************************/
  1998. VOID LowLevelHexNumpad(
  1999. WORD wScanCode,
  2000. BYTE Vk,
  2001. BOOL fBreak,
  2002. USHORT usExtraStuff)
  2003. {
  2004. if (!TestAsyncKeyStateDown(VK_MENU)) {
  2005. if (gfInNumpadHexInput & NUMPAD_HEXMODE_LL) {
  2006. gfInNumpadHexInput &= ~NUMPAD_HEXMODE_LL;
  2007. }
  2008. } else {
  2009. if (!fBreak) { // if it's key down
  2010. if ((gfInNumpadHexInput & NUMPAD_HEXMODE_LL) ||
  2011. wScanCode == SCANCODE_NUMPAD_PLUS || wScanCode == SCANCODE_NUMPAD_DOT) {
  2012. if ((usExtraStuff & KBDEXT) == 0) {
  2013. /*
  2014. * We need to check whether the input is escape character
  2015. * of hex input mode.
  2016. * This should be equivalent code as in xxxInternalToUnicode().
  2017. * If you change this code, you may need to change
  2018. * xxxInternalToUnicode() as well.
  2019. */
  2020. WORD wModBits = 0;
  2021. wModBits |= TestAsyncKeyStateDown(VK_MENU) ? KBDALT : 0;
  2022. wModBits |= TestAsyncKeyStateDown(VK_SHIFT) ? KBDSHIFT : 0;
  2023. wModBits |= TestAsyncKeyStateDown(VK_KANA) ? KBDKANA : 0;
  2024. if (MODIFIER_FOR_ALT_NUMPAD(wModBits)) {
  2025. if ((gfInNumpadHexInput & NUMPAD_HEXMODE_LL) == 0) {
  2026. /*
  2027. * Only if it's not a hotkey, we enter hex Alt+Numpad mode.
  2028. */
  2029. UINT wHotKeyMod = 0;
  2030. wHotKeyMod |= (wModBits & KBDSHIFT) ? MOD_SHIFT : 0;
  2031. wHotKeyMod |= TestAsyncKeyStateDown(VK_CONTROL) ? MOD_CONTROL : 0;
  2032. UserAssert(wModBits & KBDALT);
  2033. wHotKeyMod |= MOD_ALT;
  2034. wHotKeyMod |= TestAsyncKeyStateDown(VK_LWIN) || TestAsyncKeyStateDown(VK_RWIN) ?
  2035. MOD_WIN : 0;
  2036. if (IsHotKey(wHotKeyMod, Vk) == NULL) {
  2037. UserAssert(wScanCode == SCANCODE_NUMPAD_PLUS || wScanCode == SCANCODE_NUMPAD_DOT);
  2038. gfInNumpadHexInput |= NUMPAD_HEXMODE_LL;
  2039. }
  2040. } else if (!IsHexNumpadKeys(Vk, wScanCode)) {
  2041. gfInNumpadHexInput &= ~NUMPAD_HEXMODE_LL;
  2042. }
  2043. } else {
  2044. gfInNumpadHexInput &= ~NUMPAD_HEXMODE_LL;
  2045. }
  2046. } else {
  2047. gfInNumpadHexInput &= ~NUMPAD_HEXMODE_LL;
  2048. }
  2049. } else {
  2050. UserAssert((gfInNumpadHexInput & NUMPAD_HEXMODE_LL) == 0);
  2051. }
  2052. }
  2053. }
  2054. }
  2055. #ifdef GENERIC_INPUT
  2056. #if defined(GI_SINK)
  2057. __inline VOID FillRawKeyboardInput(
  2058. PHIDDATA pHidData,
  2059. PKEYBOARD_INPUT_DATA pkei,
  2060. UINT message,
  2061. USHORT vkey)
  2062. {
  2063. /*
  2064. * Set the data.
  2065. */
  2066. pHidData->rid.data.keyboard.MakeCode = pkei->MakeCode;
  2067. pHidData->rid.data.keyboard.Flags = pkei->Flags;
  2068. pHidData->rid.data.keyboard.Reserved = pkei->Reserved;
  2069. pHidData->rid.data.keyboard.Message = message;
  2070. pHidData->rid.data.keyboard.VKey = vkey;
  2071. pHidData->rid.data.keyboard.ExtraInformation = pkei->ExtraInformation;
  2072. }
  2073. BOOL PostRawKeyboardInput(
  2074. PQ pq,
  2075. DWORD dwTime,
  2076. HANDLE hDevice,
  2077. PKEYBOARD_INPUT_DATA pkei,
  2078. UINT message,
  2079. USHORT vkey)
  2080. {
  2081. PPROCESS_HID_TABLE pHidTable = PtiKbdFromQ(pq)->ppi->pHidTable;
  2082. PHIDDATA pHidData;
  2083. PWND pwnd;
  2084. WPARAM wParam = RIM_INPUT;
  2085. if (pHidTable && pHidTable->fRawKeyboard) {
  2086. PTHREADINFO pti;
  2087. UserAssert(PtiKbdFromQ(pq)->ppi->pHidTable);
  2088. pti = PtiKbdFromQ(pq);
  2089. pwnd = pti->ppi->pHidTable->spwndTargetKbd;
  2090. if (pwnd == NULL) {
  2091. pwnd = pq->spwndFocus;
  2092. } else {
  2093. pq = GETPTI(pwnd)->pq;
  2094. }
  2095. if (TestRawInputModeNoCheck(pti, RawKeyboard)) {
  2096. wParam = RIM_INPUT;
  2097. }
  2098. pHidData = AllocateHidData(hDevice, RIM_TYPEKEYBOARD, sizeof(RAWKEYBOARD), wParam, pwnd);
  2099. UserAssert(pq);
  2100. if (pHidData == NULL) {
  2101. // failed to allocate
  2102. RIPMSG0(RIP_WARNING, "PostRawKeyboardInput: failed to allocate HIDDATA.");
  2103. return FALSE;
  2104. }
  2105. UserAssert(pkei);
  2106. FillRawKeyboardInput(pHidData, pkei, message, vkey);
  2107. if (!PostInputMessage(pq, pwnd, WM_INPUT, RIM_INPUT, (LPARAM)PtoHq(pHidData), dwTime, pkei->ExtraInformation)) {
  2108. FreeHidData(pHidData);
  2109. }
  2110. }
  2111. #if DBG
  2112. pHidData = NULL;
  2113. #endif
  2114. if (IsKeyboardSinkPresent()) {
  2115. /*
  2116. * Walk through the global sink list.
  2117. */
  2118. PLIST_ENTRY pList = gHidRequestTable.ProcessRequestList.Flink;
  2119. PPROCESSINFO ppiForeground = PtiKbdFromQ(pq)->ppi;
  2120. for (; pList != &gHidRequestTable.ProcessRequestList; pList = pList->Flink) {
  2121. PPROCESS_HID_TABLE pProcessHidTable = CONTAINING_RECORD(pList, PROCESS_HID_TABLE, link);
  2122. UserAssert(pProcessHidTable);
  2123. if (pProcessHidTable->fRawKeyboardSink) {
  2124. /*
  2125. * Sink is specified. Let's check out if it's the legid receiver.
  2126. */
  2127. UserAssert(pProcessHidTable->spwndTargetKbd); // shouldn't be NULL.
  2128. if (pProcessHidTable->spwndTargetKbd == NULL ||
  2129. TestWF(pProcessHidTable->spwndTargetKbd, WFINDESTROY) ||
  2130. TestWF(pProcessHidTable->spwndTargetKbd, WFDESTROYED)) {
  2131. /*
  2132. * This guy doesn't have a legit spwndTarget or the window is
  2133. * halfly destroyed.
  2134. */
  2135. #ifdef LATER
  2136. pProcessHidTable->fRawKeyboard = pProcessHidTable->fRawKeyboardSink =
  2137. pProcessHidTable->fNoLegacyKeyboard = FALSE;
  2138. #endif
  2139. continue;
  2140. }
  2141. if (pProcessHidTable->spwndTargetKbd->head.rpdesk != grpdeskRitInput) {
  2142. /*
  2143. * This guy belongs to the other desktop, let's skip it.
  2144. */
  2145. continue;
  2146. }
  2147. if (GETPTI(pProcessHidTable->spwndTargetKbd)->ppi == ppiForeground) {
  2148. /*
  2149. * Should be already handled, let's skip it.
  2150. */
  2151. continue;
  2152. }
  2153. /*
  2154. * Let's post the message to this guy.
  2155. */
  2156. pHidData = AllocateHidData(hDevice, RIM_TYPEKEYBOARD, sizeof(RAWKEYBOARD), RIM_INPUTSINK, pProcessHidTable->spwndTargetKbd);
  2157. if (pHidData == NULL) {
  2158. RIPMSG1(RIP_WARNING, "PostInputMessage: failed to allocate HIDDATA for sink: %p", pProcessHidTable);
  2159. return FALSE;
  2160. }
  2161. FillRawKeyboardInput(pHidData, pkei, message, vkey);
  2162. pwnd = pProcessHidTable->spwndTargetKbd;
  2163. pq = GETPTI(pwnd)->pq;
  2164. PostInputMessage(pq, pwnd, WM_INPUT, RIM_INPUTSINK, (LPARAM)PtoHq(pHidData), dwTime, pkei->ExtraInformation);
  2165. }
  2166. }
  2167. }
  2168. return TRUE;
  2169. }
  2170. #else // GI_SINK
  2171. BOOL PostRawKeyboardInput(
  2172. PQ pq,
  2173. DWORD dwTime,
  2174. HANDLE hDevice,
  2175. PKEYBOARD_INPUT_DATA pkei,
  2176. UINT message,
  2177. USHORT vkey)
  2178. {
  2179. PHIDDATA pHidData;
  2180. PWND pwnd;
  2181. UserAssert(PtiKbdFromQ(pq)->ppi->pHidTable);
  2182. pwnd = PtiKbdFromQ(pq)->ppi->pHidTable->spwndTargetKbd;
  2183. if (pwnd == NULL) {
  2184. pwnd = pq->spwndFocus;
  2185. } else {
  2186. pq = GETPTI(pwnd)->pq;
  2187. }
  2188. pHidData = AllocateHidData(hDevice, RIM_TYPEKEYBOARD, sizeof(RAWKEYBOARD), RIM_INPUT, pwnd);
  2189. UserAssert(pq);
  2190. if (pHidData == NULL) {
  2191. // failed to allocate
  2192. RIPMSG0(RIP_WARNING, "PostRawKeyboardInput: failed to allocate HIDDATA.");
  2193. return FALSE;
  2194. }
  2195. UserAssert(hDevice);
  2196. UserAssert(pkei);
  2197. /*
  2198. * Set the data.
  2199. */
  2200. pHidData->rid.data.keyboard.MakeCode = pkei->MakeCode;
  2201. pHidData->rid.data.keyboard.Flags = pkei->Flags;
  2202. pHidData->rid.data.keyboard.Reserved = pkei->Reserved;
  2203. pHidData->rid.data.keyboard.Message = message;
  2204. pHidData->rid.data.keyboard.VKey = vkey;
  2205. pHidData->rid.data.keyboard.ExtraInformation = pkei->ExtraInformation;
  2206. PostInputMessage(pq, pwnd, WM_INPUT, RIM_INPUT, (LPARAM)PtoHq(pHidData), dwTime, pkei->ExtraInformation);
  2207. return TRUE;
  2208. }
  2209. #endif // GI_SINK
  2210. BOOL RawInputRequestedForKeyboard(PTHREADINFO pti)
  2211. {
  2212. #ifdef GI_SINK
  2213. return IsKeyboardSinkPresent() || TestRawInputMode(pti, RawKeyboard);
  2214. #else
  2215. return TestRawInputMode(pti, RawKeyboard);
  2216. #endif
  2217. }
  2218. #endif // GENERIC_INPUT
  2219. /***************************************************************************\
  2220. * xxxKeyEvent (RIT)
  2221. *
  2222. * All events from the keyboard driver go here. We receive a scan code
  2223. * from the driver and convert it to a virtual scan code and virtual
  2224. * key.
  2225. *
  2226. * The async keystate table and keylights are also updated here. Based
  2227. * on the 'focus' window we direct the input to a specific window. If
  2228. * the ALT key is down we send the events as WM_SYSKEY* messages.
  2229. *
  2230. * History:
  2231. * 10-18-90 DavidPe Created.
  2232. * 11-13-90 DavidPe WM_SYSKEY* support.
  2233. * 11-30-90 DavidPe Added keylight updating support.
  2234. * 12-05-90 DavidPe Added hotkey support.
  2235. * 03-14-91 DavidPe Moved most lParam flag support to xxxCookMessage().
  2236. * 06-07-91 DavidPe Changed to use gpqForeground rather than pwndFocus.
  2237. \***************************************************************************/
  2238. VOID xxxKeyEvent(
  2239. USHORT usFlaggedVk,
  2240. WORD wScanCode,
  2241. DWORD time,
  2242. ULONG_PTR ExtraInfo,
  2243. #ifdef GENERIC_INPUT
  2244. HANDLE hDevice,
  2245. PKEYBOARD_INPUT_DATA pkei,
  2246. #endif
  2247. BOOL bInjected)
  2248. {
  2249. USHORT message, usExtraStuff;
  2250. BOOL fBreak;
  2251. BYTE VkHanded;
  2252. BYTE Vk;
  2253. TL tlpwndActivate;
  2254. DWORD fsReserveKeys;
  2255. static BOOL fMakeAltUpASysKey;
  2256. PHOOK pHook;
  2257. PTHREADINFO ptiCurrent = PtiCurrent();
  2258. #ifdef GENERIC_INPUT
  2259. PTHREADINFO ptiKbd; // N.b. needs revalidation every time
  2260. // it leaves the critsec.
  2261. BOOL fSASHandled = FALSE;
  2262. #endif
  2263. CheckCritIn();
  2264. fBreak = usFlaggedVk & KBDBREAK;
  2265. SET_SRVIF(SRVIF_LASTRITWASKEYBOARD);
  2266. /*
  2267. * Is this a keyup or keydown event?
  2268. */
  2269. message = fBreak ? WM_KEYUP : WM_KEYDOWN;
  2270. VkHanded = (BYTE)usFlaggedVk; // get rid of state bits - no longer needed
  2271. usExtraStuff = usFlaggedVk & KBDEXT;
  2272. /*
  2273. * Convert Left/Right Ctrl/Shift/Alt key to "unhanded" key.
  2274. * ie: if VK_LCONTROL or VK_RCONTROL, convert to VK_CONTROL etc.
  2275. * Update this "unhanded" key's state if necessary.
  2276. */
  2277. if ((VkHanded >= VK_LSHIFT) && (VkHanded <= VK_RMENU)) {
  2278. BYTE VkOtherHand = VkHanded ^ 1;
  2279. Vk = (BYTE)((VkHanded - VK_LSHIFT) / 2 + VK_SHIFT);
  2280. if (!fBreak || !TestAsyncKeyStateDown(VkOtherHand)) {
  2281. if ((gptiBlockInput == NULL) || (gptiBlockInput != ptiCurrent)) {
  2282. UpdateAsyncKeyState(gpqForeground, Vk, fBreak);
  2283. }
  2284. }
  2285. } else {
  2286. Vk = VkHanded;
  2287. }
  2288. /*
  2289. * Maintain gfsSASModifiersDown to indicate which of Ctrl/Shift/Alt
  2290. * are really truly physically down
  2291. */
  2292. if (!bInjected && ((wScanCode & SCANCODE_SIMULATED) == 0)) {
  2293. if (fBreak) {
  2294. gfsSASModifiersDown &= ~VKTOMODIFIERS(Vk);
  2295. } else {
  2296. gfsSASModifiersDown |= VKTOMODIFIERS(Vk);
  2297. }
  2298. }
  2299. #ifdef GENERIC_INPUT
  2300. ptiKbd = ValidatePtiKbd(gpqForeground);
  2301. #endif
  2302. /*
  2303. * Call low level keyboard hook to see if it allows this
  2304. * message to pass
  2305. */
  2306. if ((pHook = PhkFirstValid(ptiCurrent, WH_KEYBOARD_LL)) != NULL) {
  2307. KBDLLHOOKSTRUCT kbds;
  2308. BOOL bAnsiHook;
  2309. USHORT msg = message;
  2310. USHORT usExtraLL = usExtraStuff;
  2311. #ifdef GENERIC_INPUT
  2312. UserAssert(GETPTI(pHook));
  2313. if (ptiKbd && ptiKbd->ppi == GETPTI(pHook)->ppi) {
  2314. // Skip LL hook call if the foreground application has
  2315. // a LL keyboard hook and the raw input enabled
  2316. // at the same time.
  2317. if (TestRawInputMode(ptiKbd, RawKeyboard)) {
  2318. goto skip_llhook;
  2319. }
  2320. }
  2321. #endif
  2322. /*
  2323. * Check if this is a WM_SYS* message
  2324. */
  2325. if (TestRawKeyDown(VK_MENU) &&
  2326. !TestRawKeyDown(VK_CONTROL)) {
  2327. msg += (WM_SYSKEYDOWN - WM_KEYDOWN);
  2328. usExtraLL |= 0x2000; // ALT key down
  2329. }
  2330. kbds.vkCode = (DWORD)VkHanded;
  2331. kbds.scanCode = (DWORD)wScanCode;
  2332. kbds.flags = HIBYTE(usExtraLL | (bInjected ? (LLKHF_INJECTED << 8) : 0));
  2333. kbds.flags |= (fBreak ? (KBDBREAK >> 8) : 0);
  2334. kbds.time = time;
  2335. kbds.dwExtraInfo = ExtraInfo;
  2336. if (xxxCallHook2(pHook, HC_ACTION, (DWORD)msg, (LPARAM)&kbds, &bAnsiHook)) {
  2337. UINT fsModifiers;
  2338. /*
  2339. * We can't let low level hooks or BlockInput() eat SAS
  2340. * or someone could write a trojan winlogon look alike.
  2341. */
  2342. if (IsSAS(VkHanded, &fsModifiers)) {
  2343. RIPMSG0(RIP_WARNING, "xxxKeyEvent: SAS ignore bad response from low level hook");
  2344. } else {
  2345. return;
  2346. }
  2347. }
  2348. }
  2349. #ifdef GENERIC_INPUT
  2350. skip_llhook:
  2351. #endif
  2352. /*
  2353. * If someone is blocking input and it's not us, don't allow this input
  2354. */
  2355. if (gptiBlockInput && (gptiBlockInput != ptiCurrent)) {
  2356. UINT fsModifiers;
  2357. if (IsSAS(VkHanded, &fsModifiers)) {
  2358. RIPMSG0(RIP_WARNING, "xxxKeyEvent: SAS unblocks BlockInput");
  2359. gptiBlockInput = NULL;
  2360. } else {
  2361. return;
  2362. }
  2363. }
  2364. UpdateAsyncKeyState(gpqForeground, VkHanded, fBreak);
  2365. /*
  2366. * Clear gfInNumpadHexInput if Menu key is up.
  2367. */
  2368. if (gfEnableHexNumpad && gpqForeground
  2369. #ifdef GENERIC_INPUT
  2370. && !TestRawInputMode(PtiKbdFromQ(gpqForeground), NoLegacyKeyboard)
  2371. #endif
  2372. ) {
  2373. LowLevelHexNumpad(wScanCode, Vk, fBreak, usExtraStuff);
  2374. }
  2375. /*
  2376. * If this is a make and the key is one linked to the keyboard LEDs,
  2377. * update their state.
  2378. */
  2379. if (!fBreak &&
  2380. ((Vk == VK_CAPITAL) || (Vk == VK_NUMLOCK) || (Vk == VK_SCROLL) ||
  2381. (Vk == VK_KANA && JAPANESE_KBD_LAYOUT(GetActiveHKL())))) {
  2382. /*
  2383. * Only Japanese keyboard layout could generate VK_KANA.
  2384. *
  2385. * [Comments for before]
  2386. * Since NT 3.x, UpdatesKeyLisghts() had been called for VK_KANA
  2387. * at both of 'make' and 'break' to support NEC PC-9800 Series
  2388. * keyboard hardware, but for NT 4.0, thier keyboard driver emurate
  2389. * PC/AT keyboard hardware, then this is changed to
  2390. * "Call UpdateKeyLights() only at 'make' for VK_KANA"
  2391. */
  2392. UpdateKeyLights(bInjected);
  2393. }
  2394. /*
  2395. * check for reserved keys
  2396. */
  2397. fsReserveKeys = 0;
  2398. if (gptiForeground != NULL)
  2399. fsReserveKeys = gptiForeground->fsReserveKeys;
  2400. /*
  2401. * Check the RIT's queue to see if it's doing the cool switch thing.
  2402. * Cancel if the user presses any other key.
  2403. */
  2404. if (gspwndAltTab != NULL && (!fBreak) &&
  2405. Vk != VK_TAB && Vk != VK_SHIFT && Vk != VK_MENU) {
  2406. /*
  2407. * Remove the Alt-tab window
  2408. */
  2409. xxxCancelCoolSwitch();
  2410. /*
  2411. * eat VK_ESCAPE if the app doesn't want it
  2412. */
  2413. if ((Vk == VK_ESCAPE) && !(fsReserveKeys & CONSOLE_ALTESC)) {
  2414. return;
  2415. }
  2416. }
  2417. /*
  2418. * Check for hotkeys.
  2419. */
  2420. if (xxxDoHotKeyStuff(Vk, fBreak, fsReserveKeys)) {
  2421. #ifdef GENERIC_INPUT
  2422. UINT fsModifiers;
  2423. /*
  2424. * Windows Bug 268903: DI folks want the DEL key reported
  2425. * even though it's already handled --- for the compatibility
  2426. * with the LL hook.
  2427. */
  2428. if (IsSAS(VkHanded, &fsModifiers)) {
  2429. fSASHandled = TRUE;
  2430. } else {
  2431. #endif
  2432. /*
  2433. * The hotkey was processed so don't pass on the event.
  2434. */
  2435. return;
  2436. #ifdef GENERIC_INPUT
  2437. }
  2438. #endif
  2439. }
  2440. #ifdef GENERIC_INPUT
  2441. /*
  2442. * If the foreground thread wants RawInput, post it here.
  2443. */
  2444. ptiKbd = ValidatePtiKbd(gpqForeground);
  2445. if (pkei && ptiKbd && RawInputRequestedForKeyboard(ptiKbd)) {
  2446. DWORD msg = message;
  2447. #if POST_EXTRALL
  2448. DWORD usExtraLL = usExtraStuff;
  2449. #endif
  2450. /*
  2451. * Check if this is a WM_SYS* message
  2452. */
  2453. if (TestRawKeyDown(VK_MENU) &&
  2454. !TestRawKeyDown(VK_CONTROL)) {
  2455. msg += (WM_SYSKEYDOWN - WM_KEYDOWN);
  2456. #if POST_EXTRA_LL
  2457. usExtraLL |= 0x2000; // ALT key down
  2458. #endif
  2459. }
  2460. TAGMSG3(DBGTAG_PNP, "xxxKeyEvent: posting to pwnd=%#p, vk=%02x, flag=%04x", gpqForeground->spwndFocus, Vk, pkei->Flags);
  2461. PostRawKeyboardInput(gpqForeground, time, hDevice, pkei, msg, (USHORT)Vk);
  2462. }
  2463. /*
  2464. * If SAS key is handled, this is a special case, just bail out.
  2465. */
  2466. if (fSASHandled) {
  2467. return;
  2468. }
  2469. /*
  2470. * If the foreground thread does not want the legacy input, bail out.
  2471. */
  2472. if (ptiKbd) {
  2473. if (VkHanded == 0) {
  2474. TAGMSG0(DBGTAG_PNP, "xxxKeyEvent: vkHanded is zero, bail out.");
  2475. return;
  2476. }
  2477. if (TestRawInputMode(ptiKbd, NoLegacyKeyboard)) {
  2478. if (Vk == VK_MENU || Vk == VK_TAB || gspwndAltTab != NULL) {
  2479. /*
  2480. * Special case for fast switching. We should always
  2481. * handle these hotkeys.
  2482. */
  2483. TAGMSG0(DBGTAG_PNP, "xxxKeyEvent: we'll do Alt+Tab even if the FG thread requests NoLegacy");
  2484. } else if ((TestRawInputMode(ptiKbd, AppKeys)) &&
  2485. (Vk >= VK_APPCOMMAND_FIRST && Vk <= VK_APPCOMMAND_LAST)) {
  2486. TAGMSG0(DBGTAG_PNP, "xxxKeyEvent: we'll do app commands if the FG thread requests NoLegacy and AppKeys");
  2487. } else {
  2488. TAGMSG0(DBGTAG_PNP, "xxxKeyEvent: FG thread doen't want legacy kbd. bail out");
  2489. return;
  2490. }
  2491. }
  2492. }
  2493. #endif // GENERIC_INPUT
  2494. /*
  2495. * If the ALT key is down and the CTRL key
  2496. * isn't, this is a WM_SYS* message.
  2497. */
  2498. if (TestAsyncKeyStateDown(VK_MENU) && !TestAsyncKeyStateDown(VK_CONTROL) && Vk != VK_JUNJA) {
  2499. // VK_JUNJA is ALT+'+'. Since all KOR VKs are not converted to IME hotkey IDs and
  2500. // should be passed directly to IME, KOR related VKs are not treated as SYSKEYDOWN.
  2501. message += (WM_SYSKEYDOWN - WM_KEYDOWN);
  2502. usExtraStuff |= 0x2000;
  2503. /*
  2504. * If this is the ALT-down set this flag, otherwise
  2505. * clear it since we got a key inbetween the ALT-down
  2506. * and ALT-up. (see comment below)
  2507. */
  2508. if (Vk == VK_MENU) {
  2509. fMakeAltUpASysKey = TRUE;
  2510. /*
  2511. * Unlock SetForegroundWindow (if locked) when the ALT key went down.
  2512. */
  2513. if (!fBreak) {
  2514. gppiLockSFW = NULL;
  2515. }
  2516. } else {
  2517. fMakeAltUpASysKey = FALSE;
  2518. }
  2519. } else if (Vk == VK_MENU) {
  2520. if (fBreak) {
  2521. /*
  2522. * End our switch if we are in the middle of one.
  2523. */
  2524. if (fMakeAltUpASysKey) {
  2525. /*
  2526. * We don't make the keyup of the ALT key a WM_SYSKEYUP if any
  2527. * other key is typed while the ALT key was down. I don't know
  2528. * why we do this, but it's been here since version 1 and any
  2529. * app that uses SDM relies on it (eg - opus).
  2530. *
  2531. * The Alt bit is not set for the KEYUP message either.
  2532. */
  2533. message += (WM_SYSKEYDOWN - WM_KEYDOWN);
  2534. }
  2535. if (gspwndAltTab != NULL) {
  2536. /*
  2537. * Send the alt up message before we change queues
  2538. */
  2539. if (gpqForeground != NULL) {
  2540. #ifdef GENERIC_INPUT
  2541. if (!TestRawInputMode(PtiKbdFromQ(gpqForeground), NoLegacyKeyboard)) {
  2542. #endif
  2543. /*
  2544. * Set this flag so that we know we're doing a tab-switch.
  2545. * This makes sure that both cases where the ALT-KEY is released
  2546. * before or after the TAB-KEY is handled. It is checked in
  2547. * xxxDefWindowProc().
  2548. */
  2549. gpqForeground->QF_flags |= QF_TABSWITCHING;
  2550. PostInputMessage(gpqForeground, NULL, message, (DWORD)Vk,
  2551. MAKELONG(1, (wScanCode | usExtraStuff)),
  2552. time, ExtraInfo);
  2553. #ifdef GENERIC_INPUT
  2554. }
  2555. #endif
  2556. }
  2557. /*
  2558. * Remove the Alt-tab window
  2559. */
  2560. xxxCancelCoolSwitch();
  2561. if (gspwndActivate != NULL) {
  2562. /*
  2563. * Make our selected window active and destroy our
  2564. * switch window. If the new window is minmized,
  2565. * restore it. If we are switching in the same
  2566. * queue, we clear out gpqForeground to make
  2567. * xxxSetForegroundWindow2 to change the pwnd
  2568. * and make the switch. This case will happen
  2569. * with WOW and Console apps.
  2570. */
  2571. if (gpqForeground == GETPTI(gspwndActivate)->pq) {
  2572. gpqForeground = NULL;
  2573. }
  2574. /*
  2575. * Make the selected window thread the owner of the last input;
  2576. * since the user has selected him, he owns the ALT-TAB.
  2577. */
  2578. glinp.ptiLastWoken = GETPTI(gspwndActivate);
  2579. ThreadLockAlways(gspwndActivate, &tlpwndActivate);
  2580. xxxSetForegroundWindow2(gspwndActivate, NULL,
  2581. SFW_SWITCH | SFW_ACTIVATERESTORE);
  2582. /*
  2583. * Win3.1 calls SetWindowPos() with activate, which z-orders
  2584. * first regardless, then activates. Our code relies on
  2585. * xxxActivateThisWindow() to z-order, and it'll only do
  2586. * it if the window does not have the child bit set (regardless
  2587. * that the window is a child of the desktop).
  2588. *
  2589. * To be compatible, we'll just force z-order here if the
  2590. * window has the child bit set. This z-order is asynchronous,
  2591. * so this'll z-order after the activate event is processed.
  2592. * That'll allow it to come on top because it'll be foreground
  2593. * then. (Grammatik has a top level window with the child
  2594. * bit set that wants to be come the active window).
  2595. */
  2596. if (TestWF(gspwndActivate, WFCHILD)) {
  2597. xxxSetWindowPos(gspwndActivate, (PWND)HWND_TOP, 0, 0, 0, 0,
  2598. SWP_NOSIZE | SWP_NOMOVE | SWP_ASYNCWINDOWPOS);
  2599. }
  2600. ThreadUnlock(&tlpwndActivate);
  2601. Unlock(&gspwndActivate);
  2602. }
  2603. return;
  2604. }
  2605. } else {
  2606. /*
  2607. * The ALT key is down, unlock SetForegroundWindow (if locked)
  2608. */
  2609. gppiLockSFW = NULL;
  2610. }
  2611. }
  2612. /*
  2613. * Handle switching. Eat the Key if we are doing switching.
  2614. */
  2615. if (!FJOURNALPLAYBACK() && !FJOURNALRECORD() && (!fBreak) &&
  2616. (TestAsyncKeyStateDown(VK_MENU)) &&
  2617. (!TestAsyncKeyStateDown(VK_CONTROL)) && //gpqForeground &&
  2618. (((Vk == VK_TAB) && !(fsReserveKeys & CONSOLE_ALTTAB)) ||
  2619. ((Vk == VK_ESCAPE) && !(fsReserveKeys & CONSOLE_ALTESC)))) {
  2620. xxxNextWindow(gpqForeground ? gpqForeground : gptiRit->pq, Vk);
  2621. } else if (gpqForeground != NULL) {
  2622. PQMSG pqmsgPrev = gpqForeground->mlInput.pqmsgWriteLast;
  2623. DWORD wParam = (DWORD)Vk;
  2624. LONG lParam;
  2625. #ifdef GENERIC_INPUT
  2626. if (TestRawInputMode(PtiKbdFromQ(gpqForeground), NoLegacyKeyboard)) {
  2627. if (!TestRawInputMode(PtiKbdFromQ(gpqForeground), AppKeys) ||
  2628. !(Vk >= VK_APPCOMMAND_FIRST && Vk <= VK_APPCOMMAND_LAST)) {
  2629. return;
  2630. }
  2631. }
  2632. #endif
  2633. /*
  2634. * We have a packet containing a Unicode character
  2635. * This is injected by Pen via SendInput
  2636. */
  2637. if ((Vk == VK_PACKET) && (usFlaggedVk & KBDUNICODE)) {
  2638. wParam |= (wScanCode << 16);
  2639. wScanCode = 0;
  2640. }
  2641. lParam = MAKELONG(1, (wScanCode | usExtraStuff));
  2642. /*
  2643. * WM_*KEYDOWN messages are left unchanged on the queue except the
  2644. * repeat count field (LOWORD(lParam)) is incremented.
  2645. */
  2646. if (pqmsgPrev != NULL &&
  2647. pqmsgPrev->msg.message == message &&
  2648. (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) &&
  2649. pqmsgPrev->msg.wParam == wParam &&
  2650. HIWORD(pqmsgPrev->msg.lParam) == HIWORD(lParam)) {
  2651. #ifdef GENERIC_INPUT
  2652. /*
  2653. * We shouldn't be here for a generic input keyboard that
  2654. * doesn't want legacy support.
  2655. */
  2656. UserAssert(!TestRawInputMode(PtiKbdFromQ(gpqForeground), NoLegacyKeyboard));
  2657. #endif
  2658. /*
  2659. * Increment the queued message's repeat count. This could
  2660. * conceivably overflow but Win 3.0 doesn't deal with it
  2661. * and anyone who buffers up 65536 keystrokes is a chimp
  2662. * and deserves to have it wrap anyway.
  2663. */
  2664. pqmsgPrev->msg.lParam = MAKELONG(LOWORD(pqmsgPrev->msg.lParam) + 1,
  2665. HIWORD(lParam));
  2666. WakeSomeone(gpqForeground, message, pqmsgPrev);
  2667. } else {
  2668. /*
  2669. * check if these are speedracer keys - bug 339877
  2670. * for the speedracer keys we want to post an event message and generate the
  2671. * wm_appcommand in xxxprocesseventmessage
  2672. * Since SpeedRacer software looks for the hotkeys we want to let those through
  2673. * It is going in here since we don't want the ability to eat up tons of pool memory
  2674. * so we post the event message here and then post the input message for the wm_keydown
  2675. * below - that way if the key is repeated then there is coalescing done above and no more
  2676. * qevent_appcommands are posted to the input queue.
  2677. */
  2678. if (VK_APPCOMMAND_FIRST <= Vk && Vk <= VK_APPCOMMAND_LAST) {
  2679. /*
  2680. * Only send wm_appcommands for wm_keydown (& wm_syskeydown) messages -
  2681. * essentially we ignore wm_keyup for those vk's defined for wm_appcommand messages
  2682. */
  2683. if (!fBreak && gpqForeground) {
  2684. /*
  2685. * post an event message so we can syncronize with normal types of input
  2686. * send through the vk - we will construct the message in xxxProcessEventMessage
  2687. */
  2688. PostEventMessage(gpqForeground->ptiKeyboard, gpqForeground, QEVENT_APPCOMMAND,
  2689. NULL, 0, (WPARAM)0, Vk);
  2690. }
  2691. #ifdef GENERIC_INPUT
  2692. if (TestRawInputMode(PtiKbdFromQ(gpqForeground), NoLegacyKeyboard)) {
  2693. return;
  2694. }
  2695. #endif
  2696. }
  2697. /*
  2698. * We let the key go through since we want wm_keydowns/ups to get generated for these
  2699. * SpeedRacer keys
  2700. */
  2701. if (gpqForeground->QF_flags & QF_MOUSEMOVED) {
  2702. PostMove(gpqForeground);
  2703. }
  2704. PostInputMessage(gpqForeground, NULL, message, wParam,
  2705. lParam, time, ExtraInfo);
  2706. }
  2707. }
  2708. }
  2709. /**************************************************************************\
  2710. * GetMouseCoord
  2711. *
  2712. * Calculates the coordinates of the point that will be injected.
  2713. *
  2714. * History:
  2715. * 11-01-96 CLupu Created.
  2716. * 12-18-97 MCostea MOUSE_VIRTUAL_DESKTOP support
  2717. \**************************************************************************/
  2718. VOID GetMouseCoord(
  2719. LONG dx,
  2720. LONG dy,
  2721. DWORD dwFlags,
  2722. LONG time,
  2723. ULONG_PTR ExtraInfo,
  2724. PPOINT ppt)
  2725. {
  2726. if (dwFlags & MOUSE_MOVE_ABSOLUTE) {
  2727. LONG cxMetric, cyMetric;
  2728. /*
  2729. * If MOUSE_VIRTUAL_DESKTOP was specified, map to entire virtual screen
  2730. */
  2731. if (dwFlags & MOUSE_VIRTUAL_DESKTOP) {
  2732. cxMetric = SYSMET(CXVIRTUALSCREEN);
  2733. cyMetric = SYSMET(CYVIRTUALSCREEN);
  2734. } else {
  2735. cxMetric = SYSMET(CXSCREEN);
  2736. cyMetric = SYSMET(CYSCREEN);
  2737. }
  2738. /*
  2739. * Absolute pointing device used: deltas are actually the current
  2740. * position. Update the global mouse position.
  2741. *
  2742. * Note that the position is always reported in units of
  2743. * (0,0)-(0xFFFF,0xFFFF) which corresponds to
  2744. * (0,0)-(SYSMET(CXSCREEN), SYSMET(CYSCREEN)) in pixels.
  2745. * We must first scale it to fit on the screen using the formula:
  2746. * ptScreen = ptMouse * resPrimaryMonitor / 64K
  2747. *
  2748. * The straightforward algorithm coding of this algorithm is:
  2749. *
  2750. * ppt->x = (dx * SYSMET(CXSCREEN)) / (long)0x0000FFFF;
  2751. * ppt->y = (dy * SYSMET(CYSCREEN)) / (long)0x0000FFFF;
  2752. *
  2753. * On x86, with 14 more bytes we can avoid the division function with
  2754. * the following code.
  2755. */
  2756. ppt->x = dx * cxMetric;
  2757. if (ppt->x >= 0) {
  2758. ppt->x = HIWORD(ppt->x);
  2759. } else {
  2760. ppt->x = - (long) HIWORD(-ppt->x);
  2761. }
  2762. ppt->y = dy * cyMetric;
  2763. if (ppt->y >= 0) {
  2764. ppt->y = HIWORD(ppt->y);
  2765. } else {
  2766. ppt->y = - (long) HIWORD(-ppt->y);
  2767. }
  2768. /*
  2769. * (0, 0) must map to the leftmost point on the desktop
  2770. */
  2771. if (dwFlags & MOUSE_VIRTUAL_DESKTOP) {
  2772. ppt->x += SYSMET(XVIRTUALSCREEN);
  2773. ppt->y += SYSMET(YVIRTUALSCREEN);
  2774. }
  2775. /*
  2776. * Reset the mouse sensitivity remainder.
  2777. */
  2778. idxRemainder = idyRemainder = 0;
  2779. /*
  2780. * Save the absolute coordinates in the global array
  2781. * for GetMouseMovePointsEx.
  2782. */
  2783. SAVEPOINT(dx, dy, 0xFFFF, 0xFFFF, time, ExtraInfo);
  2784. } else {
  2785. /*
  2786. * Is there any mouse acceleration to do?
  2787. */
  2788. if (gMouseSpeed != 0) {
  2789. #ifdef SUBPIXEL_MOUSE
  2790. DoNewMouseAccel(&dx, &dy);
  2791. #else
  2792. dx = DoMouseAccel(dx);
  2793. dy = DoMouseAccel(dy);
  2794. #endif
  2795. } else if (gMouseSensitivity != MOUSE_SENSITIVITY_DEFAULT) {
  2796. int iNumerator;
  2797. /*
  2798. * Does the mouse sensitivity need to be adjusted?
  2799. */
  2800. if (dx != 0) {
  2801. iNumerator = dx * gMouseSensitivityFactor + idxRemainder;
  2802. dx = iNumerator / 256;
  2803. idxRemainder = iNumerator % 256;
  2804. if ((iNumerator < 0) && (idxRemainder > 0)) {
  2805. dx++;
  2806. idxRemainder -= 256;
  2807. }
  2808. }
  2809. if (dy != 0) {
  2810. iNumerator = dy * gMouseSensitivityFactor + idyRemainder;
  2811. dy = iNumerator / 256;
  2812. idyRemainder = iNumerator % 256;
  2813. if ((iNumerator < 0) && (idyRemainder > 0)) {
  2814. dy++;
  2815. idyRemainder -= 256;
  2816. }
  2817. }
  2818. }
  2819. ppt->x += dx;
  2820. ppt->y += dy;
  2821. /*
  2822. * Save the absolute coordinates in the global array
  2823. * for GetMouseMovePointsEx.
  2824. */
  2825. SAVEPOINT(ppt->x, ppt->y,
  2826. SYSMET(CXVIRTUALSCREEN) - 1, SYSMET(CYVIRTUALSCREEN) - 1,
  2827. time, ExtraInfo);
  2828. }
  2829. }
  2830. /***************************************************************************\
  2831. * xxxMoveEventAbsolute (RIT)
  2832. *
  2833. * Mouse move events from the mouse driver are processed here. If there is a
  2834. * mouse owner window setup from xxxButtonEvent() the event is automatically
  2835. * sent there, otherwise it's sent to the window the mouse is over.
  2836. *
  2837. * Mouse acceleration happens here as well as cursor clipping (as a result of
  2838. * the ClipCursor() API).
  2839. *
  2840. * History:
  2841. * 10-18-90 DavidPe Created.
  2842. * 11-29-90 DavidPe Added mouse acceleration support.
  2843. * 01-25-91 IanJa xxxWindowHitTest change
  2844. * IanJa non-jerky mouse moves
  2845. \***************************************************************************/
  2846. #ifdef LOCK_MOUSE_CODE
  2847. #pragma alloc_text(MOUSE, xxxMoveEventAbsolute)
  2848. #endif
  2849. VOID xxxMoveEventAbsolute(
  2850. LONG x,
  2851. LONG y,
  2852. ULONG_PTR dwExtraInfo,
  2853. #ifdef GENERIC_INPUT
  2854. HANDLE hDevice,
  2855. PMOUSE_INPUT_DATA pmei,
  2856. #endif
  2857. DWORD time,
  2858. BOOL bInjected
  2859. )
  2860. {
  2861. LONG ulMoveFlags = MP_NORMAL;
  2862. CheckCritOut();
  2863. if (IsHooked(gptiRit, WHF_FROM_WH(WH_MOUSE_LL))) {
  2864. MSLLHOOKSTRUCT mslls;
  2865. BOOL bEatEvent = FALSE;
  2866. BOOL bAnsiHook;
  2867. PHOOK pHook;
  2868. mslls.pt.x = x;
  2869. mslls.pt.y = y;
  2870. mslls.mouseData = 0;
  2871. mslls.flags = bInjected;
  2872. mslls.time = time;
  2873. mslls.dwExtraInfo = dwExtraInfo;
  2874. /*
  2875. * Call low level mouse hooks to see if they allow this message
  2876. * to pass through USER
  2877. */
  2878. EnterCrit();
  2879. /*
  2880. * Check again to see if we still have the hook installed. Fix for 80477.
  2881. */
  2882. if ((pHook = PhkFirstValid(gptiRit, WH_MOUSE_LL)) != NULL) {
  2883. PTHREADINFO ptiCurrent;
  2884. bEatEvent = (xxxCallHook2(pHook, HC_ACTION, WM_MOUSEMOVE, (LPARAM)&mslls, &bAnsiHook) != 0);
  2885. ptiCurrent = PtiCurrent();
  2886. if (ptiCurrent->pcti->fsChangeBits & ptiCurrent->pcti->fsWakeMask & ~QS_SMSREPLY) {
  2887. RIPMSG1(RIP_WARNING, "xxxMoveEventAbsolute: applying changed wake bits (0x%x) during the LL hook callback",
  2888. ptiCurrent->pcti->fsChangeBits & ~QS_SMSREPLY);
  2889. SetWakeBit(ptiCurrent, ptiCurrent->pcti->fsChangeBits & ~QS_SMSREPLY);
  2890. }
  2891. }
  2892. LeaveCrit();
  2893. if (bEatEvent) {
  2894. return;
  2895. }
  2896. }
  2897. #ifdef GENERIC_INPUT
  2898. if (pmei && gpqForeground && RawInputRequestedForMouse(PtiMouseFromQ(gpqForeground))) {
  2899. EnterCrit();
  2900. PostRawMouseInput(gpqForeground, time, hDevice, pmei);
  2901. LeaveCrit();
  2902. }
  2903. #endif
  2904. /*
  2905. * Blow off the event if WH_JOURNALPLAYBACK is installed. Do not
  2906. * use FJOURNALPLAYBACK() because this routine may be called from
  2907. * multiple desktop threads and the hook check must be done
  2908. * for the rit thread, not the calling thread.
  2909. */
  2910. if (IsGlobalHooked(gptiRit, WHF_FROM_WH(WH_JOURNALPLAYBACK))) {
  2911. return;
  2912. }
  2913. /*
  2914. * For the atomicness of monitor. Let's bail out while the monitor
  2915. * is being updated by the other thread.
  2916. */
  2917. if (InterlockedCompareExchange(&gdwMonitorBusy, TRUE, FALSE) != FALSE) {
  2918. RIPMSGF0(RIP_VERBOSE, "the monitor info is being updated. We have to bail out here");
  2919. return;
  2920. }
  2921. gptCursorAsync.x = x;
  2922. gptCursorAsync.y = y;
  2923. BoundCursor(&gptCursorAsync);
  2924. /*
  2925. * Move the screen pointer.
  2926. * Pass an event source parameter as the flags so that TS
  2927. * can correctly send a mouse update to the client if the mouse
  2928. * move is originating from a shadow client or if the move is injected.
  2929. */
  2930. #ifdef GENERIC_INPUT
  2931. if (pmei && (pmei->Flags & MOUSE_TERMSRV_SRC_SHADOW)) {
  2932. ulMoveFlags = MP_TERMSRV_SHADOW;
  2933. }
  2934. else if (bInjected) {
  2935. ulMoveFlags = MP_PROCEDURAL;
  2936. }
  2937. #endif
  2938. GreMovePointer(gpDispInfo->hDev, gptCursorAsync.x, gptCursorAsync.y,
  2939. ulMoveFlags);
  2940. /*
  2941. * Save the time stamp in a global so we can use it in PostMove
  2942. */
  2943. gdwMouseMoveTimeStamp = time;
  2944. /*
  2945. * Reset the locking, so that the pMonitor update can continue
  2946. */
  2947. UserAssert(gdwMonitorBusy == TRUE);
  2948. InterlockedExchange(&gdwMonitorBusy, FALSE);
  2949. /*
  2950. * Set the number of trails to hide to gMouseTrails + 1 to avoid calling
  2951. * GreMovePointer while the mouse is moving, look at HideMouseTrails().
  2952. */
  2953. if (GETMOUSETRAILS()) {
  2954. InterlockedExchange(&gMouseTrailsToHide, gMouseTrails + 1);
  2955. }
  2956. }
  2957. /***************************************************************************\
  2958. * xxxMoveEvent (RIT)
  2959. *
  2960. * The dwFlags can be
  2961. * 0 relative move
  2962. * MOUSEEVENTF_ABSOLUTE absolute move
  2963. * MOUSEEVENTF_VIRTUALDESK the absolute coordinates will be maped
  2964. * to the entire virtual desktop. This flag makes sense only with MOUSEEVENTF_ABSOLUTE
  2965. *
  2966. \***************************************************************************/
  2967. #ifdef LOCK_MOUSE_CODE
  2968. #pragma alloc_text(MOUSE, xxxMoveEvent)
  2969. #endif
  2970. VOID xxxMoveEvent(
  2971. LONG dx,
  2972. LONG dy,
  2973. DWORD dwFlags,
  2974. ULONG_PTR dwExtraInfo,
  2975. #ifdef GENERIC_INPUT
  2976. HANDLE hDevice,
  2977. PMOUSE_INPUT_DATA pmei,
  2978. #endif
  2979. DWORD time,
  2980. BOOL bInjected)
  2981. {
  2982. POINT ptLastMove = gptCursorAsync;
  2983. CheckCritOut();
  2984. /*
  2985. * Get the actual point that will be injected.
  2986. */
  2987. GetMouseCoord(dx, dy, ConvertToMouseDriverFlags(dwFlags),
  2988. time, dwExtraInfo, &ptLastMove);
  2989. /*
  2990. * move the mouse
  2991. */
  2992. xxxMoveEventAbsolute(
  2993. ptLastMove.x,
  2994. ptLastMove.y,
  2995. dwExtraInfo,
  2996. #ifdef GENERIC_INPUT
  2997. hDevice,
  2998. pmei,
  2999. #endif
  3000. time,
  3001. bInjected);
  3002. }
  3003. /***************************************************************************\
  3004. * UpdateRawKeyState
  3005. *
  3006. * A helper routine for ProcessKeyboardInput.
  3007. * Based on a VK and a make/break flag, this function will update the physical
  3008. * keystate table.
  3009. *
  3010. * History:
  3011. * 10-13-91 IanJa Created.
  3012. \***************************************************************************/
  3013. VOID UpdateRawKeyState(
  3014. BYTE Vk,
  3015. BOOL fBreak)
  3016. {
  3017. CheckCritIn();
  3018. if (fBreak) {
  3019. ClearRawKeyDown(Vk);
  3020. } else {
  3021. /*
  3022. * This is a key make. If the key was not already down, update the
  3023. * physical toggle bit.
  3024. */
  3025. if (!TestRawKeyDown(Vk)) {
  3026. ToggleRawKeyToggle(Vk);
  3027. }
  3028. /*
  3029. * This is a make, so turn on the physical key down bit.
  3030. */
  3031. SetRawKeyDown(Vk);
  3032. }
  3033. }
  3034. VOID CleanupResources(
  3035. VOID)
  3036. {
  3037. PPCLS ppcls;
  3038. PTHREADINFO pti;
  3039. UserAssert(!gbCleanedUpResources);
  3040. gbCleanedUpResources = TRUE;
  3041. HYDRA_HINT(HH_CLEANUPRESOURCES);
  3042. /*
  3043. * Prevent power callouts.
  3044. */
  3045. CleanupPowerRequestList();
  3046. /*
  3047. * Destroy the system classes also
  3048. */
  3049. ppcls = &gpclsList;
  3050. while (*ppcls != NULL) {
  3051. DestroyClass(ppcls);
  3052. }
  3053. /*
  3054. * Unlock the cursor from all the CSRSS's threads.
  3055. * We do this here because RIT might not be the only
  3056. * CSRSS process running at this time and we want
  3057. * to prevent the change of thread ownership
  3058. * after RIT is gone.
  3059. */
  3060. pti = PpiCurrent()->ptiList;
  3061. while (pti != NULL) {
  3062. if (pti->pq != NULL) {
  3063. LockQCursor(pti->pq, NULL);
  3064. }
  3065. pti = pti->ptiSibling;
  3066. }
  3067. UnloadCursorsAndIcons();
  3068. /*
  3069. * Cleanup the GDI globals in USERK
  3070. */
  3071. CleanupGDI();
  3072. }
  3073. #if 0 // Temporariry
  3074. typedef struct _EX_RUNDOWN_WAIT_BLOCK {
  3075. ULONG Count;
  3076. KEVENT WakeEvent;
  3077. } EX_RUNDOWN_WAIT_BLOCK, *PEX_RUNDOWN_WAIT_BLOCK;
  3078. //NTKERNELAPI
  3079. VOID
  3080. FASTCALL
  3081. __ExWaitForRundownProtectionRelease (
  3082. IN PEX_RUNDOWN_REF RunRef
  3083. )
  3084. /*++
  3085. Routine Description:
  3086. Wait till all outstanding rundown protection calls have exited
  3087. Arguments:
  3088. RunRef - Pointer to a rundown structure
  3089. Return Value:
  3090. None
  3091. --*/
  3092. {
  3093. EX_RUNDOWN_WAIT_BLOCK WaitBlock;
  3094. PKEVENT Event;
  3095. ULONG_PTR Value, NewValue;
  3096. ULONG WaitCount;
  3097. #if 1
  3098. LARGE_INTEGER liTimeout;
  3099. NTSTATUS Status;
  3100. ULONG counter;
  3101. #endif
  3102. PAGED_CODE ();
  3103. //
  3104. // Fast path. this should be the normal case. If Value is zero then there are no current accessors and we have
  3105. // marked the rundown structure as rundown. If the value is EX_RUNDOWN_ACTIVE then the structure has already
  3106. // been rundown and ExRundownCompleted. This second case allows for callers that might initiate rundown
  3107. // multiple times (like handle table rundown) to have subsequent rundowns become noops.
  3108. //
  3109. Value = (ULONG_PTR) InterlockedCompareExchangePointer (&RunRef->Ptr,
  3110. (PVOID) EX_RUNDOWN_ACTIVE,
  3111. (PVOID) 0);
  3112. if (Value == 0 || Value == EX_RUNDOWN_ACTIVE) {
  3113. #if 1
  3114. RIPMSG1(RIP_WARNING, "__ExWaitForRundownProtectionRelease: rundown finished in session %d", gSessionId);
  3115. #endif
  3116. return;
  3117. }
  3118. //
  3119. // Slow path
  3120. //
  3121. Event = NULL;
  3122. #if 1
  3123. counter = 0;
  3124. #endif
  3125. do {
  3126. //
  3127. // Extract total number of waiters. Its biased by 2 so we can hanve the rundown active bit.
  3128. //
  3129. WaitCount = (ULONG) (Value >> EX_RUNDOWN_COUNT_SHIFT);
  3130. //
  3131. // If there are some accessors present then initialize and event (once only).
  3132. //
  3133. if (WaitCount > 0 && Event == NULL) {
  3134. Event = &WaitBlock.WakeEvent;
  3135. KeInitializeEvent (Event, SynchronizationEvent, FALSE);
  3136. }
  3137. //
  3138. // Store the wait count in the wait block. Waiting threads will start to decrement this as they exit
  3139. // if our exchange succeeds. Its possible for accessors to come and go between our initial fetch and
  3140. // the interlocked swap. This doesn't matter so long as there is the same number of outstanding accessors
  3141. // to wait for.
  3142. //
  3143. WaitBlock.Count = WaitCount;
  3144. NewValue = ((ULONG_PTR) &WaitBlock) | EX_RUNDOWN_ACTIVE;
  3145. NewValue = (ULONG_PTR) InterlockedCompareExchangePointer (&RunRef->Ptr,
  3146. (PVOID) NewValue,
  3147. (PVOID) Value);
  3148. if (NewValue == Value) {
  3149. if (WaitCount > 0) {
  3150. #if 1
  3151. /*
  3152. * NT Base calls take time values in 100 nanosecond units.
  3153. * Make it relative (negative)...
  3154. * Timeout in 20 minutes.
  3155. */
  3156. liTimeout.QuadPart = Int32x32To64(-10000, 300000 * 4);
  3157. Status = KeWaitForSingleObject (Event,
  3158. Executive,
  3159. KernelMode,
  3160. FALSE,
  3161. &liTimeout);
  3162. if (Status == STATUS_TIMEOUT) {
  3163. FRE_RIPMSG1(RIP_ERROR, "__ExWaitForRundownProtectionRelease: Rundown wait time out in session %d", gSessionId);
  3164. }
  3165. #endif
  3166. ASSERT (WaitBlock.Count == 0);
  3167. }
  3168. return;
  3169. }
  3170. Value = NewValue;
  3171. ASSERT ((Value&EX_RUNDOWN_ACTIVE) == 0);
  3172. #if 1
  3173. #define THRESHOLD (50000)
  3174. if (++counter > THRESHOLD) {
  3175. FRE_RIPMSG2(RIP_ERROR, "__ExWaitForRundownProtectionRelease: Rundown wait loop over %d in session %d", THRESHOLD, gSessionId);
  3176. counter = 0;
  3177. }
  3178. #endif
  3179. } while (TRUE);
  3180. }
  3181. #endif
  3182. VOID WaitForWinstaRundown(
  3183. PKEVENT pRundownEvent)
  3184. {
  3185. if (pRundownEvent) {
  3186. KeSetEvent(pRundownEvent, EVENT_INCREMENT, FALSE);
  3187. }
  3188. /*
  3189. * Wait for any WindowStation objects to get freed.
  3190. */
  3191. #if 0
  3192. /*
  3193. * HACK ALERT!
  3194. * Tentatively, we call our own copy of WaitForRundown
  3195. * to let it timeout in the target session.
  3196. */
  3197. __ExWaitForRundownProtectionRelease(&gWinstaRunRef);
  3198. #endif
  3199. ExWaitForRundownProtectionRelease(&gWinstaRunRef);
  3200. ExRundownCompleted (&gWinstaRunRef);
  3201. }
  3202. VOID SetWaitForWinstaRundown(
  3203. VOID)
  3204. {
  3205. OBJECT_ATTRIBUTES obja;
  3206. NTSTATUS Status;
  3207. HANDLE hProcess = NULL;
  3208. HANDLE hThreadWinstaRundown = NULL;
  3209. PKEVENT pRundownEvent = NULL;
  3210. pRundownEvent = CreateKernelEvent(SynchronizationEvent, FALSE);
  3211. InitializeObjectAttributes(&obja,
  3212. NULL,
  3213. 0,
  3214. NULL,
  3215. NULL);
  3216. UserAssert(gpepCSRSS != NULL);
  3217. Status = ObOpenObjectByPointer(
  3218. gpepCSRSS,
  3219. 0,
  3220. NULL,
  3221. PROCESS_CREATE_THREAD,
  3222. NULL,
  3223. KernelMode,
  3224. &hProcess);
  3225. if (!NT_SUCCESS(Status)) {
  3226. goto ExitClean;
  3227. }
  3228. UserAssert(hProcess != NULL);
  3229. Status = PsCreateSystemThread(
  3230. &hThreadWinstaRundown,
  3231. THREAD_ALL_ACCESS,
  3232. &obja,
  3233. hProcess,
  3234. NULL,
  3235. (PKSTART_ROUTINE)WaitForWinstaRundown,
  3236. pRundownEvent);
  3237. if (!NT_SUCCESS(Status)) {
  3238. goto ExitClean;
  3239. }
  3240. if (pRundownEvent) {
  3241. KeWaitForSingleObject(pRundownEvent, WrUserRequest,
  3242. KernelMode, FALSE, NULL);
  3243. } else {
  3244. UserSleep(100);
  3245. }
  3246. ExitClean:
  3247. if (pRundownEvent) {
  3248. FreeKernelEvent(&pRundownEvent);
  3249. }
  3250. if (hProcess) {
  3251. ZwClose(hProcess);
  3252. }
  3253. if (hThreadWinstaRundown) {
  3254. ZwClose(hThreadWinstaRundown);
  3255. }
  3256. }
  3257. /***************************************************************
  3258. * NumHandles
  3259. *
  3260. * This function returns the number of handles of an Ob Object.
  3261. *
  3262. * History:
  3263. * 03/29/2001 MohamB Created.
  3264. ****************************************************************/
  3265. ULONG NumHandles(
  3266. HANDLE hObjectHandle)
  3267. {
  3268. NTSTATUS Status;
  3269. OBJECT_BASIC_INFORMATION Obi;
  3270. if (hObjectHandle != NULL) {
  3271. Status = ZwQueryObject(hObjectHandle,
  3272. ObjectBasicInformation,
  3273. &Obi,
  3274. sizeof (OBJECT_BASIC_INFORMATION),
  3275. NULL);
  3276. if (Status == STATUS_SUCCESS) {
  3277. if (Obi.HandleCount > 1) {
  3278. HYDRA_HINT(HH_DTWAITONHANDLES);
  3279. }
  3280. return Obi.HandleCount;
  3281. }
  3282. }
  3283. return 0;
  3284. }
  3285. /***************************************************************************\
  3286. * InitiateWin32kCleanup (RIT)
  3287. *
  3288. * This function starts the cleanup of a win32k
  3289. *
  3290. * History:
  3291. * 04-Dec-97 clupu Created.
  3292. \***************************************************************************/
  3293. BOOL InitiateWin32kCleanup(
  3294. VOID)
  3295. {
  3296. PTHREADINFO ptiCurrent;
  3297. PWINDOWSTATION pwinsta;
  3298. BOOLEAN fWait = TRUE;
  3299. PDESKTOP pdesk;
  3300. UNICODE_STRING ustrName;
  3301. WCHAR szName[MAX_SESSION_PATH];
  3302. HANDLE hevtRitExited;
  3303. OBJECT_ATTRIBUTES obja;
  3304. NTSTATUS Status;
  3305. LARGE_INTEGER timeout;
  3306. NTSTATUS Reason;
  3307. BOOL fFirstTimeout = TRUE;
  3308. TRACE_HYDAPI(("InitiateWin32kCleanup\n"));
  3309. TAGMSG0(DBGTAG_RIT, "Exiting Win32k ...");
  3310. SetWaitForWinstaRundown();
  3311. /*
  3312. * Prevent power callouts.
  3313. */
  3314. CleanupPowerRequestList();
  3315. /*
  3316. * Unregister Device notifications for sessions attached to Physical Console
  3317. * We already do this during Session disconnection -- but if disconnect fails, we leak notifications which is not good
  3318. */
  3319. if (!IsRemoteConnection()) {
  3320. /*
  3321. * Cleanup device class notifications
  3322. */
  3323. xxxUnregisterDeviceClassNotifications();
  3324. }
  3325. EnterCrit();
  3326. gbCleanupInitiated = TRUE;
  3327. HYDRA_HINT(HH_INITIATEWIN32KCLEANUP);
  3328. ptiCurrent = PtiCurrent();
  3329. UserAssert(ptiCurrent != NULL);
  3330. pwinsta = ptiCurrent->pwinsta;
  3331. /*
  3332. * Give DTs 5 minutes to go away
  3333. */
  3334. timeout.QuadPart = Int32x32To64(-10000, 600000);
  3335. /*
  3336. * Wait for all desktops to exit other than the disconnected desktop.
  3337. */
  3338. while (fWait) {
  3339. /*
  3340. * If things are left on the destroy list or the disconnected desktop is
  3341. * not the current desktop (at the end we should always switch to the
  3342. * disconnected desktop), then wait.
  3343. */
  3344. if (pwinsta == NULL) {
  3345. break;
  3346. }
  3347. pdesk = pwinsta->rpdeskList;
  3348. if (pdesk == NULL) {
  3349. break;
  3350. }
  3351. fWait = pdesk != gspdeskDisconnect
  3352. || pdesk->rpdeskNext != NULL
  3353. || pwinsta->pTerm->rpdeskDestroy != NULL
  3354. || NumHandles(ghDisconnectDesk) > 1;
  3355. if (fWait) {
  3356. LeaveCrit();
  3357. Reason = KeWaitForSingleObject(gpevtDesktopDestroyed, WrUserRequest,
  3358. KernelMode, FALSE, &timeout);
  3359. if (Reason == STATUS_TIMEOUT) {
  3360. #if 0
  3361. /*
  3362. * The first time we timeout might be because winlogon died
  3363. * before calling ExitWindowsEx. In that case there may be processes
  3364. * w/ GUI threads running and those threads will have an hdesk
  3365. * in the THREADINFO structure. Thus the desktop threads will not exit.
  3366. * In this situation we signal the event 'EventRitStuck' so that
  3367. * csrss can tell termsrv to start killing the remaining processes
  3368. * calling NtTerminateProcess on them. csrss signals that to termsrv
  3369. * by closing the LPC port in ntuser\server\api.c (W32WinStationTerminate)
  3370. */
  3371. if (fFirstTimeout) {
  3372. HANDLE hevtRitStuck;
  3373. FRE_RIPMSG0(RIP_ERROR,
  3374. "Timeout in RIT waiting for gpevtDesktopDestroyed. Signal EventRitStuck...");
  3375. swprintf(szName, L"\\Sessions\\%ld\\BaseNamedObjects\\EventRitStuck",
  3376. gSessionId);
  3377. RtlInitUnicodeString(&ustrName, szName);
  3378. InitializeObjectAttributes(&obja,
  3379. &ustrName,
  3380. OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
  3381. NULL,
  3382. NULL);
  3383. Status = ZwCreateEvent(&hevtRitStuck,
  3384. EVENT_ALL_ACCESS,
  3385. &obja,
  3386. SynchronizationEvent,
  3387. FALSE);
  3388. UserAssert((! gbRemoteSession) || NT_SUCCESS(Status));
  3389. if (NT_SUCCESS(Status)) {
  3390. ZwSetEvent(hevtRitStuck, NULL);
  3391. ZwClose(hevtRitStuck);
  3392. fFirstTimeout = FALSE;
  3393. }
  3394. } else {
  3395. FRE_RIPMSG0(RIP_WARNING,
  3396. "Timeout in RIT waiting for gpevtDesktopDestroyed.\n"
  3397. "There are still GUI threads (assigned to a desktop) running !");
  3398. }
  3399. RIPMSG0(RIP_WARNING,
  3400. "Timeout in RIT waiting for gpevtDesktopDestroyed. Signal EventRitStuck...");
  3401. {
  3402. SYSTEM_KERNEL_DEBUGGER_INFORMATION KernelDebuggerInfo;
  3403. NTSTATUS Status;
  3404. Status = ZwQuerySystemInformation(SystemKernelDebuggerInformation,
  3405. &KernelDebuggerInfo, sizeof(KernelDebuggerInfo), NULL);
  3406. if (NT_SUCCESS(Status) && KernelDebuggerInfo.KernelDebuggerEnabled)
  3407. DbgBreakPoint();
  3408. }
  3409. #endif
  3410. }
  3411. EnterCrit();
  3412. }
  3413. }
  3414. TAGMSG0(DBGTAG_RIT, "All other desktops exited...");
  3415. Unlock(&gspwndLogonNotify);
  3416. /*
  3417. * Set ExitInProgress -- this will prevent us from posting any
  3418. * device reads in the future.
  3419. */
  3420. gbExitInProgress = TRUE;
  3421. TAGMSG2(DBGTAG_RIT, "Shutting down ptiCurrent %lx cWindows %d",
  3422. ptiCurrent, ptiCurrent->cWindows);
  3423. /*
  3424. * Clear out some values so some operations won't be possible.
  3425. */
  3426. gpqCursor = NULL;
  3427. UserAssert(gspwndScreenCapture == NULL);
  3428. Unlock(&gspwndMouseOwner);
  3429. UserAssert(gspwndMouseOwner == NULL);
  3430. UserAssert(gspwndInternalCapture == NULL);
  3431. /*
  3432. * Free any SPBs.
  3433. */
  3434. if (gpDispInfo) {
  3435. FreeAllSpbs();
  3436. }
  3437. /*
  3438. * Close the disconnected desktop.
  3439. */
  3440. if (ghDisconnectWinSta) {
  3441. UserVerify(NT_SUCCESS(ZwClose(ghDisconnectWinSta)));
  3442. ghDisconnectWinSta = NULL;
  3443. }
  3444. if (ghDisconnectDesk) {
  3445. CloseProtectedHandle(ghDisconnectDesk);
  3446. ghDisconnectDesk = NULL;
  3447. }
  3448. if (pwinsta) {
  3449. UserAssert(pwinsta->rpdeskList == NULL);
  3450. }
  3451. /*
  3452. * Unlock the logon desktop from the global variable
  3453. */
  3454. UnlockDesktop(&grpdeskLogon, LDU_DESKLOGON, 0);
  3455. /*
  3456. * Unlock the disconnect logon
  3457. *
  3458. * This was referenced when we created it, so free it now.
  3459. * This is also a flag since the disconnect code checks to see if
  3460. * the disconnected desktop is still around.
  3461. */
  3462. UnlockDesktop(&gspdeskDisconnect, LDU_DESKDISCONNECT, 0);
  3463. /*
  3464. * Unlock any windows still locked in the SMS list. We need to do
  3465. * this here because if we don't, we end up with zombie windows in the
  3466. * desktop thread that we'll try to assign to RIT but RIT will be gone.
  3467. */
  3468. {
  3469. PSMS psms = gpsmsList;
  3470. while (psms != NULL) {
  3471. if (psms->spwnd != NULL) {
  3472. UserAssert(psms->message == WM_CLIENTSHUTDOWN);
  3473. RIPMSG1(RIP_WARNING, "Window %#p locked in the SMS list",
  3474. psms->spwnd);
  3475. Unlock(&psms->spwnd);
  3476. }
  3477. psms = psms->psmsNext;
  3478. }
  3479. }
  3480. /*
  3481. * Free outstanding timers.
  3482. */
  3483. while (gptmrFirst != NULL) {
  3484. FreeTimer(gptmrFirst);
  3485. }
  3486. /*
  3487. * Free the task switch window if there.
  3488. */
  3489. if (gspwndAltTab != NULL) {
  3490. Unlock(&gspwndAltTab);
  3491. }
  3492. TAGMSG0(DBGTAG_RIT, "posting WM_QUIT to the IO DT");
  3493. if (pwinsta) {
  3494. UserAssert(pwinsta->pTerm->ptiDesktop != NULL);
  3495. UserAssert(pwinsta->pTerm == &gTermIO);
  3496. }
  3497. {
  3498. /*
  3499. * Wait for desktop thread(s) to exit.
  3500. * This thread (RIT) is used to assign
  3501. * objects if the orginal thread leaves. So it should be
  3502. * the last one to go. Hopefully, if the desktop thread
  3503. * exits, there shouldn't be any objects in use.
  3504. */
  3505. PVOID aDT[2];
  3506. ULONG cObjects = 0;
  3507. if (gTermIO.ptiDesktop != NULL) {
  3508. aDT[0] = gTermIO.ptiDesktop->pEThread;
  3509. ObReferenceObject(aDT[0]);
  3510. cObjects++;
  3511. if (!_PostThreadMessage(gTermIO.ptiDesktop, WM_QUIT, 0, 0)) {
  3512. FRE_RIPMSG1(RIP_ERROR, "InitiateWin32kCleanup: failed to post WM_QUIT message to IO desktop thread %p",
  3513. gTermIO.ptiDesktop);
  3514. }
  3515. HYDRA_HINT(HH_DTQUITPOSTED);
  3516. }
  3517. if (gTermNOIO.ptiDesktop != NULL) {
  3518. aDT[1] = gTermNOIO.ptiDesktop->pEThread;
  3519. ObReferenceObject(aDT[1]);
  3520. cObjects++;
  3521. if (!_PostThreadMessage(gTermNOIO.ptiDesktop, WM_QUIT, 0, 0)) {
  3522. FRE_RIPMSG1(RIP_ERROR, "InitiateWin32kCleanup: failed to post WM_QUIT message to NOIO desktop thread %p",
  3523. gTermNOIO.ptiDesktop);
  3524. }
  3525. }
  3526. if (cObjects > 0) {
  3527. LeaveCrit();
  3528. TAGMSG0(DBGTAG_RIT, "waiting on desktop thread(s) destruction ...");
  3529. /*
  3530. * Give DTs 5 minutes to go away
  3531. */
  3532. timeout.QuadPart = Int32x32To64(-10000, 300000);
  3533. WaitAgain:
  3534. Reason =
  3535. KeWaitForMultipleObjects(cObjects,
  3536. aDT,
  3537. WaitAll,
  3538. WrUserRequest,
  3539. KernelMode,
  3540. TRUE,
  3541. &timeout,
  3542. NULL);
  3543. if (Reason == STATUS_TIMEOUT) {
  3544. FRE_RIPMSG0(RIP_ERROR,
  3545. "InitiateWin32kCleanup: Timeout in RIT waiting for desktop threads to go away.");
  3546. goto WaitAgain;
  3547. }
  3548. TAGMSG0(DBGTAG_RIT, "Desktop thread(s) destroyed");
  3549. ObDereferenceObject(aDT[0]);
  3550. if (cObjects > 1) {
  3551. ObDereferenceObject(aDT[1]);
  3552. }
  3553. EnterCrit();
  3554. }
  3555. }
  3556. HYDRA_HINT(HH_ALLDTGONE);
  3557. /*
  3558. * If still connected, tell the miniport driver to disconnect
  3559. */
  3560. if (gbConnected) {
  3561. if (!gfRemotingConsole) {
  3562. bDrvDisconnect(gpDispInfo->hDev, ghRemoteThinwireChannel,
  3563. gThinwireFileObject);
  3564. } else{
  3565. ASSERT(!IsRemoteConnection());
  3566. ASSERT(gConsoleShadowhDev != NULL);
  3567. bDrvDisconnect(gConsoleShadowhDev, ghConsoleShadowThinwireChannel,
  3568. gConsoleShadowThinwireFileObject);
  3569. }
  3570. }
  3571. UnlockDesktop(&grpdeskRitInput, LDU_DESKRITINPUT, 0);
  3572. UnlockDesktop(&gspdeskShouldBeForeground, LDU_DESKSHOULDBEFOREGROUND, 0);
  3573. /*
  3574. * Kill the csr port so no hard errors are services after this point
  3575. */
  3576. if (CsrApiPort != NULL) {
  3577. ObDereferenceObject(CsrApiPort);
  3578. CsrApiPort = NULL;
  3579. }
  3580. Unlock(&gspwndCursor);
  3581. /*
  3582. * set this to NULL
  3583. */
  3584. gptiRit = NULL;
  3585. TAGMSG0(DBGTAG_RIT, "TERMINATING !!!");
  3586. #if DBG
  3587. {
  3588. PPROCESSINFO ppi = gppiList;
  3589. KdPrint(("Processes still running:\n"));
  3590. KdPrint(("-------------------------\n"));
  3591. while (ppi) {
  3592. PTHREADINFO pti;
  3593. KdPrint(("ppi '%s' %#p threads: %d\n",
  3594. PsGetProcessImageFileName(ppi->Process),
  3595. ppi,
  3596. ppi->cThreads));
  3597. KdPrint(("\tGUI threads\n"));
  3598. pti = ppi->ptiList;
  3599. while (pti) {
  3600. KdPrint(("\t%#p\n", pti));
  3601. pti = pti->ptiSibling;
  3602. }
  3603. ppi = ppi->ppiNextRunning;
  3604. }
  3605. KdPrint(("-------------------------\n"));
  3606. }
  3607. #endif // DBG
  3608. LeaveCrit();
  3609. if (gbRemoteSession) {
  3610. swprintf(szName, L"\\Sessions\\%ld\\BaseNamedObjects\\EventRitExited",
  3611. gSessionId);
  3612. RtlInitUnicodeString(&ustrName, szName);
  3613. InitializeObjectAttributes(&obja,
  3614. &ustrName,
  3615. OBJ_CASE_INSENSITIVE | OBJ_OPENIF,
  3616. NULL,
  3617. NULL);
  3618. Status = ZwCreateEvent(&hevtRitExited,
  3619. EVENT_ALL_ACCESS,
  3620. &obja,
  3621. SynchronizationEvent,
  3622. FALSE);
  3623. if (NT_SUCCESS(Status)) {
  3624. ZwSetEvent(hevtRitExited, NULL);
  3625. ZwClose(hevtRitExited);
  3626. } else {
  3627. RIPMSG1(RIP_ERROR, "RIT unable to create EventRitExited: 0x%x\n", Status);
  3628. }
  3629. }
  3630. /*
  3631. * Clear TIF_PALETTEAWARE or else we will AV in xxxDestroyThreadInfo
  3632. * MCostea #412136
  3633. */
  3634. ptiCurrent->TIF_flags &= ~TIF_PALETTEAWARE;
  3635. HYDRA_HINT(HH_RITGONE);
  3636. return TRUE;
  3637. }
  3638. /***************************************************************************\
  3639. * RemoteSyncToggleKeys (RIT)
  3640. *
  3641. * This function is called whenever a remote client needs to synchronize the
  3642. * current toggle key state of the server. If the keys are out of sync, it
  3643. * injects the correct toggle key sequences.
  3644. *
  3645. * History:
  3646. * 11-12-98 JParsons Created.
  3647. \***************************************************************************/
  3648. VOID RemoteSyncToggleKeys(
  3649. ULONG toggleKeys)
  3650. {
  3651. KE ke;
  3652. BOOL bInjected;
  3653. CheckCritIn();
  3654. gSetLedReceived = toggleKeys | KEYBOARD_LED_INJECTED;
  3655. #ifdef GENERIC_INPUT
  3656. ke.hDevice = NULL;
  3657. #endif
  3658. // Key injection only works if there is a ready application queue.
  3659. if (gpqForeground != NULL) {
  3660. bInjected = gSetLedReceived & KEYBOARD_SHADOW ? TRUE : FALSE;
  3661. if (!(gSetLedReceived & KEYBOARD_CAPS_LOCK_ON) != !TestRawKeyToggle(VK_CAPITAL)) {
  3662. ke.bScanCode = (BYTE)(0x3a);
  3663. ke.usFlaggedVk = VK_CAPITAL;
  3664. xxxProcessKeyEvent(&ke, 0, bInjected);
  3665. ke.bScanCode = (BYTE)(0xba & 0x7f);
  3666. ke.usFlaggedVk = VK_CAPITAL | KBDBREAK;
  3667. xxxProcessKeyEvent(&ke, 0, bInjected);
  3668. }
  3669. if (!(gSetLedReceived & KEYBOARD_NUM_LOCK_ON) != !TestRawKeyToggle(VK_NUMLOCK)) {
  3670. ke.bScanCode = (BYTE)(0x45);
  3671. ke.usFlaggedVk = VK_NUMLOCK;
  3672. xxxProcessKeyEvent(&ke, 0, bInjected);
  3673. ke.bScanCode = (BYTE)(0xc5 & 0x7f);
  3674. ke.usFlaggedVk = VK_NUMLOCK | KBDBREAK;
  3675. xxxProcessKeyEvent(&ke, 0, bInjected);
  3676. }
  3677. if (!(gSetLedReceived & KEYBOARD_SCROLL_LOCK_ON) != !TestRawKeyToggle(VK_SCROLL)) {
  3678. ke.bScanCode = (BYTE)(0x46);
  3679. ke.usFlaggedVk = VK_SCROLL;
  3680. xxxProcessKeyEvent(&ke, 0, bInjected);
  3681. ke.bScanCode = (BYTE)(0xc6 & 0x7f);
  3682. ke.usFlaggedVk = VK_SCROLL | KBDBREAK;
  3683. xxxProcessKeyEvent(&ke, 0, bInjected);
  3684. }
  3685. if (JAPANESE_KBD_LAYOUT(GetActiveHKL())) {
  3686. if (!(gSetLedReceived & KEYBOARD_KANA_LOCK_ON) != !TestRawKeyToggle(VK_KANA)) {
  3687. ke.bScanCode = (BYTE)(0x70);
  3688. ke.usFlaggedVk = VK_KANA;
  3689. xxxProcessKeyEvent(&ke, 0, bInjected);
  3690. ke.bScanCode = (BYTE)(0xf0 & 0x7f);
  3691. ke.usFlaggedVk = VK_KANA | KBDBREAK;
  3692. xxxProcessKeyEvent(&ke, 0, bInjected);
  3693. }
  3694. }
  3695. gSetLedReceived = 0;
  3696. }
  3697. }
  3698. /***************************************************************************\
  3699. * ProcessKeyboardInput (RIT)
  3700. *
  3701. * This function is called whenever a keyboard input is ready to be consumed.
  3702. * It calls xxxProcessKeyEvent() for every input event, and once all the events
  3703. * have been consumed, calls StartDeviceRead() to request more keyboard events.
  3704. *
  3705. * Return value: "OK to continue walking gpDeviceInfoList"
  3706. * TRUE - processed input without leaving gpresDeviceInfoList critical section
  3707. * FALSE - had to leave the gpresDeviceInfoList critical section
  3708. *
  3709. * History:
  3710. * 11-26-90 DavidPe Created.
  3711. \***************************************************************************/
  3712. VOID ProcessKeyboardInputWorker(
  3713. PKEYBOARD_INPUT_DATA pkei,
  3714. #ifdef GENERIC_INPUT
  3715. PDEVICEINFO pDeviceInfo,
  3716. #endif
  3717. BOOL fProcessRemap)
  3718. {
  3719. BYTE Vk;
  3720. BYTE bPrefix;
  3721. KE ke;
  3722. #ifdef GENERIC_INPUT
  3723. /*
  3724. * Set the device handle and raw data
  3725. */
  3726. ke.hDevice = PtoH(pDeviceInfo);
  3727. UserAssert(pkei);
  3728. ke.data = *pkei;
  3729. #endif
  3730. /*
  3731. * Remote terminal server clients occationally need to be able to set
  3732. * the server's toggle key state to match the client. All other
  3733. * standard keyboard inputs are processed below since this is the most
  3734. * frequent code path.
  3735. */
  3736. if ((pkei->Flags & (KEY_TERMSRV_SET_LED | KEY_TERMSRV_VKPACKET)) == 0) {
  3737. // Process any deferred remote key sync requests
  3738. if (!(gSetLedReceived & KEYBOARD_LED_INJECTED)) {
  3739. goto ProcessKeys;
  3740. } else {
  3741. RemoteSyncToggleKeys(gSetLedReceived);
  3742. }
  3743. ProcessKeys:
  3744. if (pkei->Flags & KEY_E0) {
  3745. bPrefix = 0xE0;
  3746. } else if (pkei->Flags & KEY_E1) {
  3747. bPrefix = 0xE1;
  3748. } else {
  3749. bPrefix = 0;
  3750. }
  3751. if (pkei->MakeCode == 0xFF) {
  3752. /*
  3753. * Kbd overrun (kbd hardware and/or keyboard driver) : Beep!
  3754. * (some DELL keyboards send 0xFF if keys are hit hard enough,
  3755. * presumably due to keybounce)
  3756. */
  3757. LeaveCrit();
  3758. UserBeep(440, 125);
  3759. EnterCrit();
  3760. return;
  3761. }
  3762. ke.bScanCode = (BYTE)(pkei->MakeCode & 0x7F);
  3763. if (fProcessRemap && (gpScancodeMap || gpFlexMap)) {
  3764. ke.usFlaggedVk = 0;
  3765. if (pkei->Flags & KEY_BREAK) {
  3766. ke.usFlaggedVk |= KBDBREAK;
  3767. }
  3768. if (!MapScancode(&ke, &bPrefix
  3769. #ifdef GENERIC_INPUT
  3770. , pDeviceInfo
  3771. #endif
  3772. )) {
  3773. /*
  3774. * If the input is all processed within MapScancode, go to the
  3775. * next one.
  3776. */
  3777. return;
  3778. }
  3779. }
  3780. gbVKLastDown = Vk = VKFromVSC(&ke, bPrefix, gafRawKeyState);
  3781. if (Vk == 0
  3782. #ifdef GENERIC_INPUT
  3783. && gpqForeground && !RawInputRequestedForKeyboard(PtiKbdFromQ(gpqForeground))
  3784. #endif
  3785. ) {
  3786. return;
  3787. }
  3788. if (pkei->Flags & KEY_BREAK) {
  3789. ke.usFlaggedVk |= KBDBREAK;
  3790. }
  3791. /*
  3792. * We don't know if the client system or the host should get the
  3793. * windows key, so the choice is to not support it on the host.
  3794. * (The windows key is a local key.)
  3795. *
  3796. * The other practical problem is that the local shell intercepts
  3797. * the "break" of the windows key and switches to the start menu.
  3798. * The client never sees the "break" so the host thinks the
  3799. * windows key is always depressed.
  3800. *
  3801. * Newer clients may indicate they support the windows key.
  3802. * If the client has indicated this through the gfEnableWindowsKey,
  3803. * then we allow it to be processed here on the host.
  3804. */
  3805. if (IsRemoteConnection()) {
  3806. BYTE CheckVk = (BYTE)ke.usFlaggedVk;
  3807. if (CheckVk == VK_LWIN || CheckVk == VK_RWIN) {
  3808. if (!gfEnableWindowsKey) {
  3809. return;
  3810. }
  3811. }
  3812. }
  3813. //
  3814. // Keep track of real modifier key state. Conveniently, the values for
  3815. // VK_LSHIFT, VK_RSHIFT, VK_LCONTROL, VK_RCONTROL, VK_LMENU and
  3816. // VK_RMENU are contiguous. We'll construct a bit field to keep track
  3817. // of the current modifier key state. If a bit is set, the corresponding
  3818. // modifier key is down. The bit field has the following format:
  3819. //
  3820. // +---------------------------------------------------+
  3821. // | Right | Left | Right | Left | Right | Left |
  3822. // | Alt | Alt | Control | Control | Shift | Shift |
  3823. // +---------------------------------------------------+
  3824. // 5 4 3 2 1 0 Bit
  3825. //
  3826. // Add bit 7 -- VK_RWIN
  3827. // bit 6 -- VK_LWIN
  3828. switch (Vk) {
  3829. case VK_LSHIFT:
  3830. case VK_RSHIFT:
  3831. case VK_LCONTROL:
  3832. case VK_RCONTROL:
  3833. case VK_LMENU:
  3834. case VK_RMENU:
  3835. gCurrentModifierBit = 1 << (Vk & 0xf);
  3836. break;
  3837. case VK_LWIN:
  3838. gCurrentModifierBit = 0x40;
  3839. break;
  3840. case VK_RWIN:
  3841. gCurrentModifierBit = 0x80;
  3842. break;
  3843. default:
  3844. gCurrentModifierBit = 0;
  3845. }
  3846. if (gCurrentModifierBit) {
  3847. /*
  3848. * If this is a break of a modifier key then clear the bit value.
  3849. * Otherwise, set it.
  3850. */
  3851. if (pkei->Flags & KEY_BREAK) {
  3852. gPhysModifierState &= ~gCurrentModifierBit;
  3853. } else {
  3854. gPhysModifierState |= gCurrentModifierBit;
  3855. }
  3856. }
  3857. if (!TEST_ACCF(ACCF_ACCESSENABLED)) {
  3858. xxxProcessKeyEvent(&ke, (ULONG_PTR)pkei->ExtraInformation,
  3859. pkei->Flags & KEY_TERMSRV_SHADOW ? TRUE : FALSE);
  3860. } else {
  3861. if ((gtmridAccessTimeOut != 0) && TEST_ACCESSFLAG(AccessTimeOut, ATF_TIMEOUTON)) {
  3862. gtmridAccessTimeOut = InternalSetTimer(
  3863. NULL,
  3864. gtmridAccessTimeOut,
  3865. (UINT)gAccessTimeOut.iTimeOutMSec,
  3866. xxxAccessTimeOutTimer,
  3867. TMRF_RIT | TMRF_ONESHOT
  3868. );
  3869. }
  3870. if (AccessProceduresStream(&ke, pkei->ExtraInformation, 0)) {
  3871. xxxProcessKeyEvent(&ke, (ULONG_PTR)pkei->ExtraInformation,
  3872. pkei->Flags & KEY_TERMSRV_SHADOW ? TRUE : FALSE);
  3873. }
  3874. }
  3875. } else {
  3876. // Special toggle key synchronization for Terminal Server
  3877. if (pkei->Flags & KEY_TERMSRV_SET_LED) {
  3878. if (pkei->Flags & KEY_TERMSRV_SHADOW) {
  3879. pkei->ExtraInformation |= KEYBOARD_SHADOW;
  3880. }
  3881. RemoteSyncToggleKeys(pkei->ExtraInformation);
  3882. }
  3883. if (pkei->Flags & KEY_TERMSRV_VKPACKET) {
  3884. ke.wchInjected = (WCHAR)pkei->MakeCode;
  3885. ke.usFlaggedVk = VK_PACKET | KBDUNICODE |
  3886. ((pkei->Flags & KEY_BREAK) ? KBDBREAK : 0);
  3887. xxxProcessKeyEvent(
  3888. &ke, 0,
  3889. pkei->Flags & KEY_TERMSRV_SHADOW ? TRUE : FALSE
  3890. );
  3891. }
  3892. }
  3893. }
  3894. VOID SearchAndSetKbdTbl(
  3895. PDEVICEINFO pDeviceInfo,
  3896. DWORD dwType,
  3897. DWORD dwSubType)
  3898. {
  3899. PKBDFILE pkf = gpKL->spkfPrimary;
  3900. UINT i;
  3901. if (pkf->pKbdTbl->dwType == dwType && pkf->pKbdTbl->dwSubType == dwSubType) {
  3902. goto primary_match;
  3903. }
  3904. if ((pDeviceInfo->bFlags & GDIF_NOTPNP) == 0) {
  3905. TAGMSG2(DBGTAG_KBD, "SearchAndSetKbdTbl: new type 0x%x:0x%x", dwType, dwSubType);
  3906. /*
  3907. * Search for matching keyboard layout in the current KL
  3908. */
  3909. for (i = 0; i < gpKL->uNumTbl; ++i) {
  3910. TAGMSG2(DBGTAG_KBD, "SearchAndSetKbdTbl: searching 0x%x:0x%x",
  3911. gpKL->pspkfExtra[i]->pKbdTbl->dwType,
  3912. gpKL->pspkfExtra[i]->pKbdTbl->dwSubType);
  3913. if (gpKL->pspkfExtra[i]->pKbdTbl->dwType == dwType &&
  3914. gpKL->pspkfExtra[i]->pKbdTbl->dwSubType == dwSubType) {
  3915. TAGMSG2(DBGTAG_KBD, "SearchAndSetKbdTbl: new layout for 0x%x:0x%x",
  3916. gpKL->pspkfExtra[i]->pKbdTbl->dwType,
  3917. gpKL->pspkfExtra[i]->pKbdTbl->dwSubType);
  3918. pkf = gpKL->pspkfExtra[i];
  3919. break;
  3920. }
  3921. }
  3922. if (i >= gpKL->uNumTbl) {
  3923. /*
  3924. * Unknown type to this KL.
  3925. */
  3926. TAGMSG0(DBGTAG_KBD, "ProcessKeyboardInput: cannot find the matching KL. Reactivating primary.");
  3927. }
  3928. } else {
  3929. TAGMSG0(DBGTAG_KBD, "ProcessKeyboardInput: The new keyboard is not PnP. Use primary.");
  3930. }
  3931. primary_match:
  3932. if (gpKL->spkf != pkf) {
  3933. Lock(&gpKL->spkf, pkf);
  3934. SetGlobalKeyboardTableInfo(gpKL);
  3935. }
  3936. }
  3937. VOID ProcessKeyboardInput(PDEVICEINFO pDeviceInfo)
  3938. {
  3939. PKEYBOARD_INPUT_DATA pkei;
  3940. PKEYBOARD_INPUT_DATA pkeiStart, pkeiEnd;
  3941. EnterCrit();
  3942. UserAssert(pDeviceInfo->type == DEVICE_TYPE_KEYBOARD);
  3943. UserAssert(pDeviceInfo->iosb.Information);
  3944. UserAssert(NT_SUCCESS(pDeviceInfo->iosb.Status));
  3945. /*
  3946. * Switch the keyboard layout table, if the current KL has multiple
  3947. * tables.
  3948. */
  3949. if (gpKL && gpKL->uNumTbl > 0 &&
  3950. (gpKL->dwLastKbdType != GET_KEYBOARD_DEVINFO_TYPE(pDeviceInfo) ||
  3951. gpKL->dwLastKbdSubType != GET_KEYBOARD_DEVINFO_SUBTYPE(pDeviceInfo))) {
  3952. SearchAndSetKbdTbl(pDeviceInfo,
  3953. GET_KEYBOARD_DEVINFO_TYPE(pDeviceInfo),
  3954. GET_KEYBOARD_DEVINFO_SUBTYPE(pDeviceInfo));
  3955. /*
  3956. * Whether or not we found the match, cache the type/subtype so that
  3957. * we will not try to find the same type/subtype for a while.
  3958. */
  3959. gpKL->dwLastKbdType = GET_KEYBOARD_DEVINFO_TYPE(pDeviceInfo);
  3960. gpKL->dwLastKbdSubType = GET_KEYBOARD_DEVINFO_SUBTYPE(pDeviceInfo);
  3961. }
  3962. pkeiStart = pDeviceInfo->keyboard.Data;
  3963. pkeiEnd = (PKEYBOARD_INPUT_DATA)((PBYTE)pkeiStart + pDeviceInfo->iosb.Information);
  3964. for (pkei = pkeiStart; pkei < pkeiEnd; pkei++) {
  3965. ProcessKeyboardInputWorker(pkei,
  3966. #ifdef GENERIC_INPUT
  3967. pDeviceInfo,
  3968. #endif
  3969. TRUE);
  3970. }
  3971. LeaveCrit();
  3972. }
  3973. /***************************************************************************\
  3974. * xxxProcessKeyEvent (RIT)
  3975. *
  3976. * This function is called to process an individual keystroke (up or down).
  3977. * It performs some OEM, language and layout specific processing which
  3978. * discards or modifies the keystroke or introduces additional keystrokes.
  3979. * The RawKeyState is updated here, also termination of screen saver and video
  3980. * power down is initiated here.
  3981. * xxxKeyEvent() is called for each resulting keystroke.
  3982. *
  3983. * History:
  3984. * 11-26-90 DavidPe Created.
  3985. \***************************************************************************/
  3986. VOID xxxProcessKeyEvent(
  3987. PKE pke,
  3988. ULONG_PTR ExtraInformation,
  3989. BOOL bInjected)
  3990. {
  3991. BYTE Vk;
  3992. CheckCritIn();
  3993. Vk = (BYTE)pke->usFlaggedVk;
  3994. /*
  3995. * KOREAN:
  3996. * Check this is Korean keyboard layout, or not..
  3997. *
  3998. * NOTE:
  3999. * It would be better check this by "keyboard hardware" or
  4000. * "keyboard layout" ???
  4001. *
  4002. * 1. Check by hardware :
  4003. *
  4004. * if (KOREAN_KEYBOARD(gKeyboardInfo.KeyboardIdentifier)) {
  4005. *
  4006. * 2. Check by layout :
  4007. *
  4008. * if (KOREAN_KBD_LAYOUT(_GetKeyboardLayout(0L))) {
  4009. */
  4010. if (KOREAN_KBD_LAYOUT(GetActiveHKL())) {
  4011. if ((pke->usFlaggedVk & KBDBREAK) &&
  4012. !(pke->usFlaggedVk & KBDUNICODE) &&
  4013. (pke->bScanCode == 0xF1 || pke->bScanCode == 0xF2) &&
  4014. !TestRawKeyDown(Vk)) {
  4015. /*
  4016. * This is actually a keydown with a scancode of 0xF1 or 0xF2 from a
  4017. * Korean keyboard. Korean IMEs and apps want a WM_KEYDOWN with a
  4018. * scancode of 0xF1 or 0xF2. They don't mind not getting the WM_KEYUP.
  4019. * Don't update physical keystate to allow a real 0x71/0x72 keydown.
  4020. */
  4021. pke->usFlaggedVk &= ~KBDBREAK;
  4022. } else {
  4023. UpdateRawKeyState(Vk, pke->usFlaggedVk & KBDBREAK);
  4024. }
  4025. } else {
  4026. UpdateRawKeyState(Vk, pke->usFlaggedVk & KBDBREAK);
  4027. }
  4028. /*
  4029. * Convert Left/Right Ctrl/Shift/Alt key to "unhanded" key.
  4030. * ie: if VK_LCONTROL or VK_RCONTROL, convert to VK_CONTROL etc.
  4031. */
  4032. if ((Vk >= VK_LSHIFT) && (Vk <= VK_RMENU)) {
  4033. Vk = (BYTE)((Vk - VK_LSHIFT) / 2 + VK_SHIFT);
  4034. UpdateRawKeyState(Vk, pke->usFlaggedVk & KBDBREAK);
  4035. }
  4036. /*
  4037. * Setup to shutdown screen saver and exit video power down mode.
  4038. */
  4039. if (glinp.dwFlags & LINP_POWERTIMEOUTS) {
  4040. /*
  4041. * Call video driver here to exit power down mode.
  4042. */
  4043. TAGMSG0(DBGTAG_Power, "Exit video power down mode");
  4044. DrvSetMonitorPowerState(gpDispInfo->pmdev, PowerDeviceD0);
  4045. }
  4046. glinp.dwFlags = (glinp.dwFlags & ~(LINP_INPUTTIMEOUTS | LINP_INPUTSOURCES)) | LINP_KEYBOARD;
  4047. gpsi->dwLastRITEventTickCount = NtGetTickCount();
  4048. if (!gbBlockSendInputResets || !bInjected) {
  4049. glinp.timeLastInputMessage = gpsi->dwLastRITEventTickCount;
  4050. }
  4051. if (gpsi->dwLastRITEventTickCount - gpsi->dwLastSystemRITEventTickCountUpdate > SYSTEM_RIT_EVENT_UPDATE_PERIOD) {
  4052. SharedUserData->LastSystemRITEventTickCount = gpsi->dwLastRITEventTickCount;
  4053. gpsi->dwLastSystemRITEventTickCountUpdate = gpsi->dwLastRITEventTickCount;
  4054. }
  4055. if (!bInjected || (pke->dwTime == 0)) {
  4056. pke->dwTime = glinp.timeLastInputMessage;
  4057. }
  4058. #ifdef MOUSE_IP
  4059. /*
  4060. * Sonar
  4061. */
  4062. CheckCritIn();
  4063. #ifdef KBDMAPPEDVK
  4064. if ((pke->usFlaggedVk & KBDMAPPEDVK) == 0) {
  4065. #endif
  4066. /*
  4067. * Sonar is not activated for simulated modifier keys
  4068. */
  4069. if ((pke->usFlaggedVk & KBDBREAK) == 0) {
  4070. /*
  4071. * Key down:
  4072. * When the key is down, sonar needs to be stopped.
  4073. */
  4074. if (IS_SONAR_ACTIVE()) {
  4075. StopSonar();
  4076. }
  4077. /*
  4078. * Do not process the repeated keys...
  4079. * If this key is not pressed before, remember it for the key up event.
  4080. */
  4081. if (gbLastVkForSonar != Vk) {
  4082. gbLastVkForSonar = Vk;
  4083. }
  4084. } else {
  4085. /*
  4086. * Key up:
  4087. */
  4088. if ((BYTE)Vk == gbVkForSonarKick && (BYTE)Vk == gbLastVkForSonar && TestUP(MOUSESONAR)) {
  4089. /*
  4090. * If this is keyup and it is the Sonar key, and it's the last key downed,
  4091. * kick the sonar now.
  4092. */
  4093. StartSonar();
  4094. }
  4095. /*
  4096. * Clear the last VK for the next key event.
  4097. */
  4098. CLEAR_SONAR_LASTVK();
  4099. }
  4100. #ifdef KBDMAPPEDVK
  4101. }
  4102. #endif
  4103. #endif
  4104. /*
  4105. * Now call all the OEM- and Locale- specific KEProcs.
  4106. * If KEProcs return FALSE, the keystroke has been discarded, in
  4107. * which case don't pass the key event on to xxxKeyEvent().
  4108. */
  4109. if (pke->usFlaggedVk & KBDUNICODE) {
  4110. xxxKeyEvent(pke->usFlaggedVk, pke->wchInjected,
  4111. pke->dwTime, ExtraInformation,
  4112. #ifdef GENERIC_INPUT
  4113. NULL,
  4114. NULL,
  4115. #endif
  4116. bInjected);
  4117. } else {
  4118. if (KEOEMProcs(pke) && xxxKELocaleProcs(pke) && xxxKENLSProcs(pke,ExtraInformation)) {
  4119. xxxKeyEvent(pke->usFlaggedVk, pke->bScanCode,
  4120. pke->dwTime, ExtraInformation,
  4121. #ifdef GENERIC_INPUT
  4122. pke->hDevice,
  4123. &pke->data,
  4124. #endif
  4125. bInjected);
  4126. }
  4127. }
  4128. }
  4129. #ifndef SUBPIXEL_MOUSE
  4130. /***************************************************************************\
  4131. * DoMouseAccel (RIT)
  4132. *
  4133. * History:
  4134. * 11-29-90 DavidPe Created.
  4135. \***************************************************************************/
  4136. #ifdef LOCK_MOUSE_CODE
  4137. #pragma alloc_text(MOUSE, DoMouseAccel)
  4138. #endif
  4139. LONG DoMouseAccel(
  4140. LONG Delta)
  4141. {
  4142. LONG newDelta = Delta;
  4143. if (abs(Delta) > gMouseThresh1) {
  4144. newDelta *= 2;
  4145. if ((abs(Delta) > gMouseThresh2) && (gMouseSpeed == 2)) {
  4146. newDelta *= 2;
  4147. }
  4148. }
  4149. return newDelta;
  4150. }
  4151. #endif
  4152. /***************************************************************************\
  4153. * PwndForegroundCapture
  4154. *
  4155. * History:
  4156. * 10-23-91 DavidPe Created.
  4157. \***************************************************************************/
  4158. PWND PwndForegroundCapture(VOID)
  4159. {
  4160. if (gpqForeground != NULL) {
  4161. return gpqForeground->spwndCapture;
  4162. }
  4163. return NULL;
  4164. }
  4165. /***************************************************************************\
  4166. * SetKeyboardRate
  4167. *
  4168. * This function calls the keyboard driver to set a new keyboard repeat
  4169. * rate and delay. It limits the values to the min and max given by
  4170. * the driver so it won't return an error when we call it.
  4171. *
  4172. * History:
  4173. * 11-29-90 DavidPe Created.
  4174. \***************************************************************************/
  4175. VOID SetKeyboardRate(
  4176. UINT nKeySpeedAndDelay
  4177. )
  4178. {
  4179. UINT nKeyDelay;
  4180. UINT nKeySpeed;
  4181. nKeyDelay = (nKeySpeedAndDelay & KDELAY_MASK) >> KDELAY_SHIFT;
  4182. nKeySpeed = KSPEED_MASK & nKeySpeedAndDelay;
  4183. gktp.Rate = (USHORT)( ( gKeyboardInfo.KeyRepeatMaximum.Rate -
  4184. gKeyboardInfo.KeyRepeatMinimum.Rate
  4185. ) * nKeySpeed / KSPEED_MASK
  4186. ) +
  4187. gKeyboardInfo.KeyRepeatMinimum.Rate;
  4188. gktp.Delay = (USHORT)( ( gKeyboardInfo.KeyRepeatMaximum.Delay -
  4189. gKeyboardInfo.KeyRepeatMinimum.Delay
  4190. ) * nKeyDelay / (KDELAY_MASK >> KDELAY_SHIFT)
  4191. ) +
  4192. gKeyboardInfo.KeyRepeatMinimum.Delay;
  4193. /*
  4194. * Hand off the IOCTL to the RIT, since only the system process can
  4195. * access keyboard handles
  4196. */
  4197. gdwUpdateKeyboard |= UPDATE_KBD_TYPEMATIC;
  4198. }
  4199. /***************************************************************************\
  4200. * UpdateKeyLights
  4201. *
  4202. * This function calls the keyboard driver to set the keylights into the
  4203. * current state specified by the async keystate table.
  4204. *
  4205. * bInjected: (explanation from John Parsons via email)
  4206. * Set this TRUE if you do something on the server to asynchronously change the
  4207. * indicators behind the TS client's back, to get this reflected back to the
  4208. * client. Examples are toggling num lock or caps lock programatically, or our
  4209. * favorite example is the automatic spelling correction on Word: if you type
  4210. * "tHE mouse went up the clock", Word will fix it by automagically pressing
  4211. * CAPS LOCK, then retyping the T -- if the client is not informed, the keys
  4212. * get out of sync.
  4213. * Set this to FALSE for indicator changes initiated by the client (let's say by
  4214. * pressing CAPS LOCK) in which case we don't loop back the indicator change
  4215. * since the client has already changed state locally.
  4216. *
  4217. * History:
  4218. * 11-29-90 DavidPe Created.
  4219. \***************************************************************************/
  4220. VOID UpdateKeyLights(BOOL bInjected)
  4221. {
  4222. /*
  4223. * Looking at async keystate. Must be in critical section.
  4224. */
  4225. CheckCritIn();
  4226. /*
  4227. * Based on the toggle bits in the async keystate table,
  4228. * set the key lights.
  4229. */
  4230. gklp.LedFlags = 0;
  4231. if (TestAsyncKeyStateToggle(VK_CAPITAL)) {
  4232. gklp.LedFlags |= KEYBOARD_CAPS_LOCK_ON;
  4233. SetRawKeyToggle(VK_CAPITAL);
  4234. } else {
  4235. ClearRawKeyToggle(VK_CAPITAL);
  4236. }
  4237. if (TestAsyncKeyStateToggle(VK_NUMLOCK)) {
  4238. gklp.LedFlags |= KEYBOARD_NUM_LOCK_ON;
  4239. SetRawKeyToggle(VK_NUMLOCK);
  4240. } else {
  4241. ClearRawKeyToggle(VK_NUMLOCK);
  4242. }
  4243. if (TestAsyncKeyStateToggle(VK_SCROLL)) {
  4244. gklp.LedFlags |= KEYBOARD_SCROLL_LOCK_ON;
  4245. SetRawKeyToggle(VK_SCROLL);
  4246. } else {
  4247. ClearRawKeyToggle(VK_SCROLL);
  4248. }
  4249. /*
  4250. * Only "Japanese keyboard hardware" has "KANA" LEDs, and switch to
  4251. * "KANA" state.
  4252. */
  4253. if (JAPANESE_KEYBOARD(gKeyboardInfo.KeyboardIdentifier)) {
  4254. if (TestAsyncKeyStateToggle(VK_KANA)) {
  4255. gklp.LedFlags |= KEYBOARD_KANA_LOCK_ON;
  4256. SetRawKeyToggle(VK_KANA);
  4257. } else {
  4258. ClearRawKeyToggle(VK_KANA);
  4259. }
  4260. }
  4261. /*
  4262. * On terminal server, we need to tell the WD about application injected
  4263. * toggle keys so it can update the client accordingly.
  4264. */
  4265. if (IsRemoteConnection()) {
  4266. if (bInjected)
  4267. gklp.LedFlags |= KEYBOARD_LED_INJECTED;
  4268. else
  4269. gklp.LedFlags &= ~KEYBOARD_LED_INJECTED;
  4270. }
  4271. if (PtiCurrent() != gptiRit) {
  4272. /*
  4273. * Hand off the IOCTL to the RIT, since only the system process can
  4274. * access the keyboard handles. Happens when applying user's profile.
  4275. * IanJa: Should we check PpiCurrent() == gptiRit->ppi instead?
  4276. */
  4277. gdwUpdateKeyboard |= UPDATE_KBD_LEDS;
  4278. } else {
  4279. /*
  4280. * Do it immediately (avoids a small delay between keydown and LED
  4281. * on when typing)
  4282. */
  4283. PDEVICEINFO pDeviceInfo;
  4284. EnterDeviceInfoListCrit();
  4285. for (pDeviceInfo = gpDeviceInfoList; pDeviceInfo; pDeviceInfo = pDeviceInfo->pNext) {
  4286. if ((pDeviceInfo->type == DEVICE_TYPE_KEYBOARD) && (pDeviceInfo->handle)) {
  4287. ZwDeviceIoControlFile(pDeviceInfo->handle, NULL, NULL, NULL,
  4288. &giosbKbdControl, IOCTL_KEYBOARD_SET_INDICATORS,
  4289. (PVOID)&gklp, sizeof(gklp), NULL, 0);
  4290. }
  4291. }
  4292. LeaveDeviceInfoListCrit();
  4293. if (gfRemotingConsole) {
  4294. ZwDeviceIoControlFile(ghConsoleShadowKeyboardChannel, NULL, NULL, NULL,
  4295. &giosbKbdControl, IOCTL_KEYBOARD_SET_INDICATORS,
  4296. (PVOID)&gklp, sizeof(gklp), NULL, 0);
  4297. }
  4298. }
  4299. }
  4300. /*
  4301. * _GetKeyboardType is obsolete API. The API cannot
  4302. * deal with the multiple keyboards attached.
  4303. * This API returns the best guess that older apps
  4304. * would expect.
  4305. */
  4306. int _GetKeyboardType(int nTypeFlag)
  4307. {
  4308. switch (nTypeFlag) {
  4309. case 0:
  4310. if (gpKL) {
  4311. DWORD dwType;
  4312. //
  4313. // If there's gpKL, use its primary
  4314. // type info rather than the one used
  4315. // last time.
  4316. //
  4317. UserAssert(gpKL->spkfPrimary);
  4318. UserAssert(gpKL->spkfPrimary->pKbdTbl);
  4319. dwType = gpKL->spkfPrimary->pKbdTbl->dwType;
  4320. if (dwType != 0 && dwType != KEYBOARD_TYPE_UNKNOWN) {
  4321. return dwType;
  4322. }
  4323. }
  4324. return gKeyboardInfo.KeyboardIdentifier.Type;
  4325. case 1:
  4326. // FE_SB
  4327. {
  4328. int OEMId = 0;
  4329. DWORD dwSubType;
  4330. PKBDNLSTABLES pKbdNlsTbl = gpKbdNlsTbl;
  4331. //
  4332. // If there's gpKL, use its primary value
  4333. // rather than the one used last time.
  4334. //
  4335. if (gpKL) {
  4336. UserAssert(gpKL->spkfPrimary);
  4337. if (gpKL->spkfPrimary->pKbdNlsTbl) {
  4338. pKbdNlsTbl =gpKL->spkfPrimary->pKbdNlsTbl;
  4339. }
  4340. UserAssert(gpKL->spkfPrimary->pKbdTbl);
  4341. dwSubType = gpKL->spkfPrimary->pKbdTbl->dwSubType;
  4342. } else {
  4343. dwSubType = gKeyboardInfo.KeyboardIdentifier.Subtype;
  4344. }
  4345. //
  4346. // If this keyboard layout is compatible with 101 or 106
  4347. // Japanese keyboard, we just return 101 or 106's keyboard
  4348. // id, not this keyboard's one to let application handle
  4349. // this keyboard as 101 or 106 Japanese keyboard.
  4350. //
  4351. if (pKbdNlsTbl) {
  4352. if (pKbdNlsTbl->LayoutInformation & NLSKBD_INFO_EMURATE_101_KEYBOARD) {
  4353. return MICROSOFT_KBD_101_TYPE;
  4354. }
  4355. if (pKbdNlsTbl->LayoutInformation & NLSKBD_INFO_EMURATE_106_KEYBOARD) {
  4356. return MICROSOFT_KBD_106_TYPE;
  4357. }
  4358. }
  4359. //
  4360. // PSS ID Number: Q130054
  4361. // Article last modified on 05-16-1995
  4362. //
  4363. // 3.10 1.20 | 3.50 1.20
  4364. // WINDOWS | WINDOWS NT
  4365. //
  4366. // ---------------------------------------------------------------------
  4367. // The information in this article applies to:
  4368. // - Microsoft Windows Software Development Kit (SDK) for Windows
  4369. // version 3.1
  4370. // - Microsoft Win32 Software Development Kit (SDK) version 3.5
  4371. // - Microsoft Win32s version 1.2
  4372. // ---------------------------------------------------------------------
  4373. // SUMMARY
  4374. // =======
  4375. // Because of the variety of computer manufacturers (NEC, Fujitsu, IBMJ, and
  4376. // so on) in Japan, sometimes Windows-based applications need to know which
  4377. // OEM (original equipment manufacturer) manufactured the computer that is
  4378. // running the application. This article explains how.
  4379. //
  4380. // MORE INFORMATION
  4381. // ================
  4382. // There is no documented way to detect the manufacturer of the computer that
  4383. // is currently running an application. However, a Windows-based application
  4384. // can detect the type of OEM Windows by using the return value of the
  4385. // GetKeyboardType() function.
  4386. //
  4387. // If an application uses the GetKeyboardType API, it can get OEM ID by
  4388. // specifying "1" (keyboard subtype) as argument of the function. Each OEM ID
  4389. // is listed here:
  4390. //
  4391. // OEM Windows OEM ID
  4392. // ------------------------------
  4393. // Microsoft 00H (DOS/V)
  4394. // all AX 01H
  4395. // EPSON 04H
  4396. // Fujitsu 05H
  4397. // IBMJ 07H
  4398. // Matsushita 0AH
  4399. // NEC 0DH
  4400. // Toshiba 12H
  4401. //
  4402. // Application programs can use these OEM IDs to distinguish the type of OEM
  4403. // Windows. Note, however, that this method is not documented, so Microsoft
  4404. // may not support it in the future version of Windows.
  4405. //
  4406. // As a rule, application developers should write hardware-independent code,
  4407. // especially when making Windows-based applications. If they need to make a
  4408. // hardware-dependent application, they must prepare the separated program
  4409. // file for each different hardware architecture.
  4410. //
  4411. // Additional reference words: 3.10 1.20 3.50 1.20 kbinf
  4412. // KBCategory: kbhw
  4413. // KBSubcategory: wintldev
  4414. // =============================================================================
  4415. // Copyright Microsoft Corporation 1995.
  4416. if (pKbdNlsTbl) {
  4417. //
  4418. // Get OEM (Windows) ID.
  4419. //
  4420. OEMId = ((int)pKbdNlsTbl->OEMIdentifier) << 8;
  4421. }
  4422. //
  4423. // The format of KeyboardIdentifier.Subtype :
  4424. //
  4425. // 0 - 3 bits = keyboard subtype
  4426. // 4 - 7 bits = kernel mode kerboard driver provider id.
  4427. //
  4428. // Kernel mode keyboard dirver provier | ID
  4429. // ------------------------------------+-----
  4430. // Microsoft | 00H
  4431. // all AX | 01H
  4432. // Toshiba | 02H
  4433. // EPSON | 04H
  4434. // Fujitsu | 05H
  4435. // IBMJ | 07H
  4436. // Matsushita | 0AH
  4437. // NEC | 0DH
  4438. //
  4439. //
  4440. // And here is the format of return value.
  4441. //
  4442. // 0 - 7 bits = Keyboard Subtype.
  4443. // 8 - 15 bits = OEM (Windows) Id.
  4444. // 16 - 31 bits = not used.
  4445. //
  4446. return (int)(OEMId | (dwSubType & 0x0f));
  4447. }
  4448. case 2:
  4449. return gKeyboardInfo.NumberOfFunctionKeys;
  4450. }
  4451. return 0;
  4452. }
  4453. /**************************************************************************\
  4454. * xxxMouseEventDirect
  4455. *
  4456. * Mouse event inserts a mouse event into the input stream.
  4457. *
  4458. * The parameters are the same as the fields of the MOUSEINPUT structure
  4459. * used in SendInput.
  4460. *
  4461. * dx Delta x
  4462. * dy Delta y
  4463. * mouseData Mouse wheel movement or xbuttons
  4464. * dwMEFlags Mouse event flags
  4465. * dwExtraInfo Extra info from driver.
  4466. *
  4467. * History:
  4468. * 07-23-92 Mikehar Created.
  4469. * 01-08-93 JonPa Made it work with new mouse drivers
  4470. \**************************************************************************/
  4471. BOOL xxxMouseEventDirect(
  4472. DWORD dx,
  4473. DWORD dy,
  4474. DWORD mouseData,
  4475. DWORD dwMEFlags,
  4476. DWORD dwTime,
  4477. ULONG_PTR dwExtraInfo)
  4478. {
  4479. DWORD dwDriverMouseFlags;
  4480. DWORD dwDriverMouseData;
  4481. #ifdef GENERIC_INPUT
  4482. MOUSE_INPUT_DATA mei;
  4483. #endif
  4484. PTHREADINFO pti = PtiCurrent();
  4485. if (dwTime == 0) {
  4486. dwTime = NtGetTickCount();
  4487. }
  4488. /*
  4489. * The calling thread must be on the active desktop
  4490. * and have journal playback access to that desktop.
  4491. */
  4492. if (pti->rpdesk == grpdeskRitInput) {
  4493. UserAssert(!(pti->rpdesk->rpwinstaParent->dwWSF_Flags & WSF_NOIO));
  4494. if (!CheckGrantedAccess(pti->amdesk, DESKTOP_JOURNALPLAYBACK)) {
  4495. RIPNTERR0(STATUS_ACCESS_DENIED, RIP_WARNING,
  4496. "mouse_event(): No DESKTOP_JOURNALPLAYBACK access to input desktop.");
  4497. return FALSE;
  4498. }
  4499. } else {
  4500. /*
  4501. * 3/22/95 BradG - Only allow below HACK for pre 4.0 applications
  4502. */
  4503. if (LOWORD(pti->dwExpWinVer) >= VER40) {
  4504. RIPMSG0(RIP_VERBOSE,"mouse_event(): Calls not forwarded for 4.0 or greater apps.");
  4505. return FALSE;
  4506. } else {
  4507. BOOL fAccessToDesktop;
  4508. /*
  4509. * 3/22/95 BradG - Bug #9314: Screensavers are not deactivated by mouse_event()
  4510. * The main problem is the check above, since screensavers run on their own
  4511. * desktop. This causes the above check to fail because the process using
  4512. * mouse_event() is running on another desktop. The solution is to determine
  4513. * if we have access to the input desktop by calling _OpenDesktop for the
  4514. * current input desktop, grpdeskRitInput, with a request for DESKTOP_JOURNALPLAYBACK
  4515. * access. If this succeeds, we can allow this mouse_event() request to pass
  4516. * through, otherwise return.
  4517. */
  4518. UserAssert(grpdeskRitInput != NULL);
  4519. UserAssert(!(grpdeskRitInput->rpwinstaParent->dwWSF_Flags & WSF_NOIO));
  4520. fAccessToDesktop = AccessCheckObject(grpdeskRitInput,
  4521. DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS | DESKTOP_JOURNALPLAYBACK,
  4522. KernelMode,
  4523. &DesktopMapping);
  4524. if (!fAccessToDesktop) {
  4525. RIPMSG0(RIP_VERBOSE, "mouse_event(): Call NOT forwarded to input desktop" );
  4526. return FALSE;
  4527. }
  4528. /*
  4529. * We do have access to the desktop, so
  4530. * let this mouse_event() call go through.
  4531. */
  4532. RIPMSG0( RIP_VERBOSE, "mouse_event(): Call forwarded to input desktop" );
  4533. }
  4534. }
  4535. /*
  4536. * This process is providing input so it gets the right to
  4537. * call SetForegroundWindow
  4538. */
  4539. gppiInputProvider = pti->ppi;
  4540. /*
  4541. * The following code assumes that MOUSEEVENTF_MOVE == 1,
  4542. * that MOUSEEVENTF_ABSOLUTE > all button flags, and that the
  4543. * mouse_event button flags are defined in the same order as the
  4544. * MOUSE_INPUT_DATA button bits.
  4545. */
  4546. #if MOUSEEVENTF_MOVE != 1
  4547. # error("MOUSEEVENTF_MOVE != 1")
  4548. #endif
  4549. #if MOUSEEVENTF_LEFTDOWN != MOUSE_LEFT_BUTTON_DOWN * 2
  4550. # error("MOUSEEVENTF_LEFTDOWN != MOUSE_LEFT_BUTTON_DOWN * 2")
  4551. #endif
  4552. #if MOUSEEVENTF_LEFTUP != MOUSE_LEFT_BUTTON_UP * 2
  4553. # error("MOUSEEVENTF_LEFTUP != MOUSE_LEFT_BUTTON_UP * 2")
  4554. #endif
  4555. #if MOUSEEVENTF_RIGHTDOWN != MOUSE_RIGHT_BUTTON_DOWN * 2
  4556. # error("MOUSEEVENTF_RIGHTDOWN != MOUSE_RIGHT_BUTTON_DOWN * 2")
  4557. #endif
  4558. #if MOUSEEVENTF_RIGHTUP != MOUSE_RIGHT_BUTTON_UP * 2
  4559. # error("MOUSEEVENTF_RIGHTUP != MOUSE_RIGHT_BUTTON_UP * 2")
  4560. #endif
  4561. #if MOUSEEVENTF_MIDDLEDOWN != MOUSE_MIDDLE_BUTTON_DOWN * 2
  4562. # error("MOUSEEVENTF_MIDDLEDOWN != MOUSE_MIDDLE_BUTTON_DOWN * 2")
  4563. #endif
  4564. #if MOUSEEVENTF_MIDDLEUP != MOUSE_MIDDLE_BUTTON_UP * 2
  4565. # error("MOUSEEVENTF_MIDDLEUP != MOUSE_MIDDLE_BUTTON_UP * 2")
  4566. #endif
  4567. #if MOUSEEVENTF_WHEEL != MOUSE_WHEEL * 2
  4568. # error("MOUSEEVENTF_WHEEL != MOUSE_WHEEL * 2")
  4569. #endif
  4570. /* set legal values */
  4571. dwDriverMouseFlags = dwMEFlags & MOUSEEVENTF_BUTTONMASK;
  4572. /* remove MOUSEEVENTF_XDOWN/UP because we are going to add
  4573. MOUSEEVENTF_DRIVER_X1/2DOWN/UP later */
  4574. dwDriverMouseFlags &= ~(MOUSEEVENTF_XDOWN | MOUSEEVENTF_XUP);
  4575. dwDriverMouseData = 0;
  4576. /*
  4577. * Handle mouse wheel and xbutton inputs.
  4578. *
  4579. * Note that MOUSEEVENTF_XDOWN/UP and MOUSEEVENTF_MOUSEWHEEL cannot both
  4580. * be specified since they share the mouseData field
  4581. */
  4582. if ( ((dwMEFlags & (MOUSEEVENTF_XDOWN | MOUSEEVENTF_WHEEL)) == (MOUSEEVENTF_XDOWN | MOUSEEVENTF_WHEEL)) ||
  4583. ((dwMEFlags & (MOUSEEVENTF_XUP | MOUSEEVENTF_WHEEL)) == (MOUSEEVENTF_XUP | MOUSEEVENTF_WHEEL))) {
  4584. RIPMSG1(RIP_WARNING, "Can't specify both MOUSEEVENTF_XDOWN/UP and MOUSEEVENTF_WHEEL in call to SendInput, dwFlags=0x%.8X", dwMEFlags);
  4585. dwDriverMouseFlags &= ~(MOUSEEVENTF_XDOWN | MOUSEEVENTF_XUP | MOUSEEVENTF_WHEEL);
  4586. } else if (dwMEFlags & MOUSEEVENTF_WHEEL) {
  4587. /*
  4588. * Force the value to a short. We cannot fail if it is out of range
  4589. * because we accepted a 32 bit value in NT 4.
  4590. */
  4591. dwDriverMouseData = min(max(SHRT_MIN, (LONG)mouseData), SHRT_MAX);
  4592. } else {
  4593. /* don't process xbuttons if mousedata has invalid buttons */
  4594. if (~XBUTTON_MASK & mouseData) {
  4595. RIPMSG1(RIP_WARNING, "Invalid xbutton specified in SendInput, mouseData=0x%.8X", mouseData);
  4596. } else {
  4597. if (dwMEFlags & MOUSEEVENTF_XDOWN) {
  4598. if (mouseData & XBUTTON1) {
  4599. dwDriverMouseFlags |= MOUSEEVENTF_DRIVER_X1DOWN;
  4600. }
  4601. if (mouseData & XBUTTON2) {
  4602. dwDriverMouseFlags |= MOUSEEVENTF_DRIVER_X2DOWN;
  4603. }
  4604. }
  4605. if (dwMEFlags & MOUSEEVENTF_XUP) {
  4606. if (mouseData & XBUTTON1) {
  4607. dwDriverMouseFlags |= MOUSEEVENTF_DRIVER_X1UP;
  4608. }
  4609. if (mouseData & XBUTTON2) {
  4610. dwDriverMouseFlags |= MOUSEEVENTF_DRIVER_X2UP;
  4611. }
  4612. }
  4613. }
  4614. }
  4615. /* Convert the MOUSEEVENTF_ flags to MOUSE_BUTTON flags sent by the driver */
  4616. dwDriverMouseFlags >>= 1;
  4617. #ifdef GENERIC_INPUT
  4618. mei.UnitId = INJECTED_UNIT_ID;
  4619. if (dwMEFlags & MOUSEEVENTF_ABSOLUTE) {
  4620. mei.Flags = MOUSE_MOVE_ABSOLUTE;
  4621. } else {
  4622. mei.Flags = MOUSE_MOVE_RELATIVE;
  4623. }
  4624. if (dwMEFlags & MOUSEEVENTF_VIRTUALDESK) {
  4625. mei.Flags |= MOUSE_VIRTUAL_DESKTOP;
  4626. }
  4627. mei.Buttons = dwDriverMouseFlags;
  4628. if (dwDriverMouseData) {
  4629. mei.ButtonData = (USHORT)dwDriverMouseData;
  4630. }
  4631. mei.RawButtons = 0; // LATER...
  4632. mei.LastX = dx;
  4633. mei.LastY = dy;
  4634. mei.ExtraInformation = (ULONG)dwExtraInfo;
  4635. #endif
  4636. LeaveCrit();
  4637. /*
  4638. * Process coordinates first. This is especially useful for absolute
  4639. * pointing devices like touch-screens and tablets.
  4640. */
  4641. if (dwMEFlags & MOUSEEVENTF_MOVE) {
  4642. TAGMSG2(DBGTAG_PNP, "xxxMouseEventDirect: posting mouse move msg: Flag=%04x MouseData=%04x",
  4643. mei.Flags, mei.Buttons);
  4644. xxxMoveEvent(dx, dy, dwMEFlags, dwExtraInfo,
  4645. #ifdef GENERIC_INPUT
  4646. /*
  4647. * This is a simulated input from SendInput API.
  4648. * There is no real mouse device associated with this input,
  4649. * so we can only pass NULL as a hDevice.
  4650. */
  4651. NULL,
  4652. &mei,
  4653. #endif
  4654. dwTime, TRUE);
  4655. }
  4656. TAGMSG2(DBGTAG_PNP, "xxxMoveEvent: queueing mouse msg: Flag=%04x MouseData=%04x",
  4657. mei.Flags, mei.Buttons);
  4658. QueueMouseEvent(
  4659. (USHORT) dwDriverMouseFlags,
  4660. (USHORT) dwDriverMouseData,
  4661. dwExtraInfo,
  4662. gptCursorAsync,
  4663. dwTime,
  4664. #ifdef GENERIC_INPUT
  4665. NULL,
  4666. &mei,
  4667. #endif
  4668. TRUE,
  4669. FALSE
  4670. );
  4671. ProcessQueuedMouseEvents();
  4672. EnterCrit();
  4673. return TRUE;
  4674. }
  4675. /**************************************************************************\
  4676. * xxxInternalKeyEventDirect
  4677. *
  4678. * key event inserts a key event into the input stream.
  4679. *
  4680. * History:
  4681. * 07-23-92 Mikehar Created.
  4682. \**************************************************************************/
  4683. BOOL xxxInternalKeyEventDirect(
  4684. BYTE bVk,
  4685. WORD wScan,
  4686. DWORD dwFlags,
  4687. DWORD dwTime,
  4688. ULONG_PTR dwExtraInfo)
  4689. {
  4690. PTHREADINFO pti = PtiCurrent();
  4691. KE KeyEvent;
  4692. /*
  4693. * The calling thread must be on the active desktop
  4694. * and have journal playback access to that desktop.
  4695. */
  4696. if (pti->rpdesk != grpdeskRitInput ||
  4697. !(ISCSRSS() ||
  4698. RtlAreAllAccessesGranted(pti->amdesk, DESKTOP_JOURNALPLAYBACK))) {
  4699. RIPNTERR0(STATUS_ACCESS_DENIED, RIP_WARNING,
  4700. "Injecting key failed: Non active desktop or access denied");
  4701. return FALSE;
  4702. }
  4703. UserAssert(!(pti->rpdesk->rpwinstaParent->dwWSF_Flags & WSF_NOIO));
  4704. KeyEvent.bScanCode = (BYTE)wScan;
  4705. #ifdef GENERIC_INPUT
  4706. /*
  4707. * This is a injected key, no real device is associated with this...
  4708. */
  4709. KeyEvent.hDevice = NULL;
  4710. #endif
  4711. if (dwFlags & KEYEVENTF_SCANCODE) {
  4712. bVk = VKFromVSC(&KeyEvent,
  4713. (BYTE)(dwFlags & KEYEVENTF_EXTENDEDKEY ? 0xE0 : 0),
  4714. gafRawKeyState);
  4715. KeyEvent.usFlaggedVk = (USHORT)bVk;
  4716. } else {
  4717. KeyEvent.usFlaggedVk = bVk | KBDINJECTEDVK;
  4718. }
  4719. if (dwFlags & KEYEVENTF_KEYUP)
  4720. KeyEvent.usFlaggedVk |= KBDBREAK;
  4721. if (dwFlags & KEYEVENTF_UNICODE) {
  4722. KeyEvent.usFlaggedVk |= KBDUNICODE;
  4723. KeyEvent.wchInjected = wScan;
  4724. } else if (dwFlags & KEYEVENTF_EXTENDEDKEY) {
  4725. KeyEvent.usFlaggedVk |= KBDEXT;
  4726. } else {
  4727. // Is it from the numeric keypad?
  4728. if (((bVk >= VK_NUMPAD0) && (bVk <= VK_NUMPAD9)) || (bVk == VK_DECIMAL)) {
  4729. KeyEvent.usFlaggedVk |= KBDNUMPAD;
  4730. } else {
  4731. int i;
  4732. for (i = 0; ausNumPadCvt[i] != 0; i++) {
  4733. if (bVk == LOBYTE(ausNumPadCvt[i])) {
  4734. KeyEvent.usFlaggedVk |= KBDNUMPAD;
  4735. break;
  4736. }
  4737. }
  4738. }
  4739. }
  4740. #ifdef GENERIC_INPUT
  4741. /*
  4742. * Let's simulate the input as far as we can.
  4743. */
  4744. KeyEvent.data.MakeCode = (BYTE)wScan;
  4745. if (dwFlags & KEYEVENTF_KEYUP) {
  4746. KeyEvent.data.Flags = KEY_BREAK;
  4747. } else {
  4748. KeyEvent.data.Flags = KEY_MAKE;
  4749. }
  4750. if (dwFlags & KEYEVENTF_EXTENDEDKEY) {
  4751. KeyEvent.data.Flags |= KEY_E0;
  4752. }
  4753. KeyEvent.data.Reserved = 0;
  4754. KeyEvent.data.UnitId = INJECTED_UNIT_ID;
  4755. KeyEvent.data.ExtraInformation = (ULONG)dwExtraInfo;
  4756. #endif
  4757. /*
  4758. * This process is providing input so it gets the right to
  4759. * call SetForegroundWindow
  4760. */
  4761. gppiInputProvider = pti->ppi;
  4762. KeyEvent.dwTime = dwTime;
  4763. xxxProcessKeyEvent(&KeyEvent, dwExtraInfo, TRUE);
  4764. return TRUE;
  4765. }
  4766. /*****************************************************************************\
  4767. *
  4768. * _BlockInput()
  4769. *
  4770. * This disables/enables input into USER via keyboard or mouse
  4771. * If input is enabled and the caller
  4772. * is disabling it, the caller gets the 'input cookie.' This means two
  4773. * things:
  4774. * (a) Only the caller's thread can reenable input
  4775. * (b) Only the caller's thread can fake input messages by calling
  4776. * SendInput().
  4777. *
  4778. * This guarantees a sequential uninterrupted input stream.
  4779. *
  4780. * It can be used in conjunction with a journal playback hook however,
  4781. * since USER still does some processing in *_event functions before
  4782. * noticing a journal playback hook is around.
  4783. *
  4784. * Note that the disabled state can be suspended, and will be, when the
  4785. * fault dialog comes up. ForceInputState() will save away the enabled
  4786. * status, so input is cleared, then whack back the old stuff when done.
  4787. * We do the same thing for capture, modality, blah blah. This makes sure
  4788. * that if somebody is hung, the end user can still type Ctrl+Alt+Del and
  4789. * interact with the dialog.
  4790. *
  4791. \*****************************************************************************/
  4792. BOOL
  4793. _BlockInput(BOOL fBlockIt)
  4794. {
  4795. PTHREADINFO ptiCurrent;
  4796. ptiCurrent = PtiCurrent();
  4797. /*
  4798. * The calling thread must be on the active desktop and have journal
  4799. * playback access to that desktop if it wants to block input.
  4800. * (Unblocking is less restricted)
  4801. */
  4802. if (fBlockIt &&
  4803. (ptiCurrent->rpdesk != grpdeskRitInput ||
  4804. !RtlAreAllAccessesGranted(ptiCurrent->amdesk, DESKTOP_JOURNALPLAYBACK))) {
  4805. RIPNTERR0(STATUS_ACCESS_DENIED, RIP_WARNING,
  4806. "BlockInput failed: Non active desktop or access denied");
  4807. return FALSE;
  4808. }
  4809. UserAssert(!(ptiCurrent->rpdesk->rpwinstaParent->dwWSF_Flags & WSF_NOIO));
  4810. /*
  4811. * If we are enabling input
  4812. * * Is it disabled? No, then fail the call
  4813. * * Is it disabled but we aren't the dude in control? Yes, then
  4814. * fail the call.
  4815. * If we are disabling input
  4816. * * Is it enabled? No, then fail the call
  4817. * * Set us up as the dude in control
  4818. */
  4819. if (fBlockIt) {
  4820. /*
  4821. * Is input blocked right now?
  4822. */
  4823. if (gptiBlockInput != NULL) {
  4824. return FALSE;
  4825. }
  4826. /*
  4827. * Is this thread exiting? If so, fail the call now. User's
  4828. * cleanup code won't get a chance to whack this back if so.
  4829. */
  4830. if (ptiCurrent->TIF_flags & TIF_INCLEANUP) {
  4831. return FALSE;
  4832. }
  4833. /*
  4834. * Set blocking on.
  4835. */
  4836. gptiBlockInput = ptiCurrent;
  4837. } else {
  4838. /*
  4839. * Fail if input is not blocked, or blocked by another thread
  4840. */
  4841. if (gptiBlockInput != ptiCurrent) {
  4842. return FALSE;
  4843. }
  4844. /*
  4845. * This thread was blocking input, so now clear the block.
  4846. */
  4847. gptiBlockInput = NULL;
  4848. }
  4849. return TRUE;
  4850. }
  4851. /**************************************************************************\
  4852. * xxxSendInput
  4853. *
  4854. * input injection
  4855. *
  4856. * History:
  4857. * 11-01-96 CLupu Created.
  4858. \**************************************************************************/
  4859. UINT xxxSendInput(
  4860. UINT nInputs,
  4861. LPINPUT pInputs)
  4862. {
  4863. UINT nEv;
  4864. LPINPUT pEvent;
  4865. BOOLEAN fCanDiscontinue = Is510Compat(PtiCurrent()->dwExpWinVer);
  4866. for (nEv = 0, pEvent = pInputs; nEv < nInputs; nEv++) {
  4867. switch (pEvent->type) {
  4868. case INPUT_MOUSE:
  4869. if (!xxxMouseEventDirect(
  4870. pEvent->mi.dx,
  4871. pEvent->mi.dy,
  4872. pEvent->mi.mouseData,
  4873. pEvent->mi.dwFlags,
  4874. pEvent->mi.time,
  4875. pEvent->mi.dwExtraInfo) &&
  4876. fCanDiscontinue) {
  4877. /*
  4878. * Note: the error code should have been assigned in
  4879. * xxx.*EventDirect routines, so we should just
  4880. * bail out.
  4881. */
  4882. RIPMSG0(RIP_WARNING, "xxxMouseEventDirect: failed");
  4883. goto discontinue;
  4884. }
  4885. break;
  4886. case INPUT_KEYBOARD:
  4887. if ((pEvent->ki.dwFlags & KEYEVENTF_UNICODE) &&
  4888. (pEvent->ki.wVk == 0) &&
  4889. ((pEvent->ki.dwFlags & ~(KEYEVENTF_KEYUP | KEYEVENTF_UNICODE)) == 0)) {
  4890. if (!xxxInternalKeyEventDirect(
  4891. VK_PACKET,
  4892. pEvent->ki.wScan, // actually a Unicode character
  4893. pEvent->ki.dwFlags,
  4894. pEvent->ki.time,
  4895. pEvent->ki.dwExtraInfo) &&
  4896. fCanDiscontinue) {
  4897. goto discontinue;
  4898. }
  4899. } else {
  4900. if (!xxxInternalKeyEventDirect(
  4901. LOBYTE(pEvent->ki.wVk),
  4902. LOBYTE(pEvent->ki.wScan),
  4903. pEvent->ki.dwFlags,
  4904. pEvent->ki.time,
  4905. pEvent->ki.dwExtraInfo) &&
  4906. fCanDiscontinue) {
  4907. goto discontinue;
  4908. }
  4909. }
  4910. break;
  4911. case INPUT_HARDWARE:
  4912. if (fCanDiscontinue) {
  4913. /*
  4914. * Not supported on NT.
  4915. */
  4916. RIPERR0(ERROR_CALL_NOT_IMPLEMENTED, RIP_WARNING, "xxxSendInput: INPUT_HARDWARE is for 9x only.");
  4917. goto discontinue;
  4918. }
  4919. break;
  4920. }
  4921. pEvent++;
  4922. }
  4923. discontinue:
  4924. return nEv;
  4925. }
  4926. /**************************************************************************\
  4927. * _SetConsoleReserveKeys
  4928. *
  4929. * Sets the reserved keys field in the console's pti.
  4930. *
  4931. * History:
  4932. * 02-17-93 JimA Created.
  4933. \**************************************************************************/
  4934. BOOL _SetConsoleReserveKeys(
  4935. PWND pwnd,
  4936. DWORD fsReserveKeys)
  4937. {
  4938. GETPTI(pwnd)->fsReserveKeys = fsReserveKeys;
  4939. return TRUE;
  4940. }
  4941. /**************************************************************************\
  4942. * _GetMouseMovePointsEx
  4943. *
  4944. * Gets the last nPoints mouse moves from the global buffer starting with
  4945. * ppt. Returns -1 if it doesn't find it. It uses the timestamp if it was
  4946. * provided to differentiate between mouse points with the same coordinates.
  4947. *
  4948. * History:
  4949. * 03-17-97 CLupu Created.
  4950. \**************************************************************************/
  4951. int _GetMouseMovePointsEx(
  4952. CONST MOUSEMOVEPOINT* ppt,
  4953. MOUSEMOVEPOINT* ccxpptBuf,
  4954. UINT nPoints,
  4955. DWORD resolution)
  4956. {
  4957. UINT uInd, uStart, nPointsRetrieved, i;
  4958. BOOL bFound = FALSE;
  4959. int x, y;
  4960. DWORD resX, resY;
  4961. /*
  4962. * Search the point in the global buffer and get the first occurance.
  4963. */
  4964. uInd = uStart = PREVPOINT(gptInd);
  4965. do {
  4966. /*
  4967. * The resolutions can be zero only if the buffer is still not full
  4968. */
  4969. if (HIWORD(gaptMouse[uInd].x) == 0 || HIWORD(gaptMouse[uInd].y) == 0) {
  4970. break;
  4971. }
  4972. resX = (DWORD)HIWORD(gaptMouse[uInd].x) + 1;
  4973. resY = (DWORD)HIWORD(gaptMouse[uInd].y) + 1;
  4974. if ((int)resX != SYSMET(CXVIRTUALSCREEN)) {
  4975. UserAssert(resX == 0x10000);
  4976. x = LOWORD(gaptMouse[uInd].x) * SYSMET(CXVIRTUALSCREEN) / resX;
  4977. } else {
  4978. x = LOWORD(gaptMouse[uInd].x);
  4979. }
  4980. if ((int)resY != SYSMET(CYVIRTUALSCREEN)) {
  4981. UserAssert(resY == 0x10000);
  4982. y = LOWORD(gaptMouse[uInd].y) * SYSMET(CYVIRTUALSCREEN) / resY;
  4983. } else {
  4984. y = LOWORD(gaptMouse[uInd].y);
  4985. }
  4986. if (x == ppt->x && y == ppt->y) {
  4987. /*
  4988. * If the timestamp was provided check to see if it's the right
  4989. * timestamp.
  4990. */
  4991. if (ppt->time != 0 && ppt->time != gaptMouse[uInd].time) {
  4992. uInd = PREVPOINT(uInd);
  4993. RIPMSG4(RIP_VERBOSE,
  4994. "GetMouseMovePointsEx: Found point (%x, %x) but timestamp %x diff from %x",
  4995. x, y, ppt->time, gaptMouse[uInd].time);
  4996. continue;
  4997. }
  4998. bFound = TRUE;
  4999. break;
  5000. }
  5001. uInd = PREVPOINT(uInd);
  5002. } while (uInd != uStart);
  5003. /*
  5004. * The point might not be in the buffer anymore.
  5005. */
  5006. if (!bFound) {
  5007. RIPERR2(ERROR_POINT_NOT_FOUND, RIP_VERBOSE,
  5008. "GetMouseMovePointsEx: point not found (%x, %x)", ppt->x, ppt->y);
  5009. return -1;
  5010. }
  5011. /*
  5012. * See how many points we can retrieve.
  5013. */
  5014. nPointsRetrieved = (uInd <= uStart ? uInd + MAX_MOUSEPOINTS - uStart : uInd - uStart);
  5015. nPointsRetrieved = min(nPointsRetrieved, nPoints);
  5016. /*
  5017. * Copy the points to the app buffer.
  5018. */
  5019. try {
  5020. for (i = 0; i < nPointsRetrieved; i++) {
  5021. resX = (DWORD)HIWORD(gaptMouse[uInd].x) + 1;
  5022. resY = (DWORD)HIWORD(gaptMouse[uInd].y) + 1;
  5023. /*
  5024. * If one of the resolutions is 0 then we're done.
  5025. */
  5026. if (HIWORD(gaptMouse[uInd].x) == 0 || HIWORD(gaptMouse[uInd].y) == 0) {
  5027. break;
  5028. }
  5029. /*
  5030. * LOWORD(gaptMouse[uInd].x) contains the x point on the scale
  5031. * specified by HIWORD(gaptMouse[uInd].x).
  5032. */
  5033. if (resolution == GMMP_USE_HIGH_RESOLUTION_POINTS) {
  5034. ccxpptBuf[i].x = (DWORD)LOWORD(gaptMouse[uInd].x) * 0xFFFF / (resX - 1);
  5035. ccxpptBuf[i].y = (DWORD)LOWORD(gaptMouse[uInd].y) * 0xFFFF / (resY - 1);
  5036. } else {
  5037. UserAssert(resolution == GMMP_USE_DISPLAY_POINTS);
  5038. ccxpptBuf[i].x = LOWORD(gaptMouse[uInd].x) * SYSMET(CXVIRTUALSCREEN) / resX;
  5039. ccxpptBuf[i].y = LOWORD(gaptMouse[uInd].y) * SYSMET(CYVIRTUALSCREEN) / resY;
  5040. }
  5041. ccxpptBuf[i].time = gaptMouse[uInd].time;
  5042. ccxpptBuf[i].dwExtraInfo = gaptMouse[uInd].dwExtraInfo;
  5043. uInd = PREVPOINT(uInd);
  5044. }
  5045. } except(W32ExceptionHandler(FALSE, RIP_WARNING)) {
  5046. }
  5047. return i;
  5048. }
  5049. /**************************************************************************\
  5050. * ProcessQueuedMouseEvents
  5051. *
  5052. * Process mouse events.
  5053. *
  5054. * History:
  5055. * 11-01-96 CLupu Created.
  5056. \**************************************************************************/
  5057. VOID ProcessQueuedMouseEvents(
  5058. VOID)
  5059. {
  5060. MOUSEEVENT MouseEvent;
  5061. static POINT ptCursorLast = {0,0};
  5062. while (UnqueueMouseEvent(&MouseEvent)) {
  5063. EnterCrit();
  5064. // Setup to shutdown screen saver and exit video power down mode.
  5065. if (glinp.dwFlags & LINP_POWERTIMEOUTS) {
  5066. // Call video driver here to exit power down mode.
  5067. TAGMSG0(DBGTAG_Power, "Exit video power down mode");
  5068. DrvSetMonitorPowerState(gpDispInfo->pmdev, PowerDeviceD0);
  5069. }
  5070. glinp.dwFlags &= ~(LINP_INPUTTIMEOUTS | LINP_INPUTSOURCES);
  5071. gpsi->dwLastRITEventTickCount = MouseEvent.time;
  5072. if (!gbBlockSendInputResets || !MouseEvent.bInjected) {
  5073. glinp.timeLastInputMessage = MouseEvent.time;
  5074. }
  5075. if (gpsi->dwLastRITEventTickCount - gpsi->dwLastSystemRITEventTickCountUpdate > SYSTEM_RIT_EVENT_UPDATE_PERIOD) {
  5076. SharedUserData->LastSystemRITEventTickCount = gpsi->dwLastRITEventTickCount;
  5077. gpsi->dwLastSystemRITEventTickCountUpdate = gpsi->dwLastRITEventTickCount;
  5078. }
  5079. CLEAR_SRVIF(SRVIF_LASTRITWASKEYBOARD);
  5080. gpsi->ptCursor = MouseEvent.ptPointer;
  5081. #ifdef GENERIC_INPUT
  5082. if ((gpqForeground && TestRawInputMode(PtiMouseFromQ(gpqForeground), RawMouse))
  5083. #ifdef GI_SINK
  5084. || IsMouseSinkPresent()
  5085. #endif
  5086. ) {
  5087. PostRawMouseInput(gpqForeground, MouseEvent.time, MouseEvent.hDevice, &MouseEvent.rawData);
  5088. }
  5089. #endif
  5090. if ((ptCursorLast.x != gpsi->ptCursor.x) ||
  5091. (ptCursorLast.y != gpsi->ptCursor.y)) {
  5092. /*
  5093. * This mouse move ExtraInfo is global (as ptCursor
  5094. * was) and is associated with the current ptCursor
  5095. * position. ExtraInfo is sent from the driver - pen
  5096. * win people use it.
  5097. */
  5098. gdwMouseMoveExtraInfo = MouseEvent.ExtraInfo;
  5099. ptCursorLast = gpsi->ptCursor;
  5100. /*
  5101. * Wake up someone. xxxSetFMouseMoved() clears
  5102. * dwMouseMoveExtraInfo, so we must then restore it.
  5103. */
  5104. #ifdef GENERIC_INPUT
  5105. #ifdef GI_SINK
  5106. if (IsMouseSinkPresent()) {
  5107. PostRawMouseInput(gpqForeground, MouseEvent.time, MouseEvent.hDevice, &MouseEvent.rawData);
  5108. }
  5109. #endif
  5110. if (gpqForeground == NULL || !TestRawInputMode(PtiMouseFromQ(gpqForeground), NoLegacyMouse)) {
  5111. zzzSetFMouseMoved();
  5112. }
  5113. #else
  5114. zzzSetFMouseMoved();
  5115. #endif
  5116. gdwMouseMoveExtraInfo = MouseEvent.ExtraInfo;
  5117. }
  5118. if (MouseEvent.ButtonFlags != 0) {
  5119. xxxDoButtonEvent(&MouseEvent);
  5120. }
  5121. LeaveCrit();
  5122. }
  5123. }
  5124. /***************************************************************************\
  5125. * RawInputThread (RIT)
  5126. *
  5127. * This is the RIT. It gets low-level/raw input from the device drivers
  5128. * and posts messages the appropriate queue. It gets the input via APC
  5129. * calls requested by calling NtReadFile() for the keyboard and mouse
  5130. * drivers. Basically it makes the first calls to Start*Read() and then
  5131. * sits in an NtWaitForSingleObject() loop which allows the APC calls to
  5132. * occur.
  5133. *
  5134. * All functions called exclusively on the RIT will have (RIT) next to
  5135. * the name in the header.
  5136. *
  5137. * History:
  5138. * 10-18-90 DavidPe Created.
  5139. * 11-26-90 DavidPe Rewrote to stop using POS layer.
  5140. \***************************************************************************/
  5141. #if DBG
  5142. DWORD gBlockDelay = 0;
  5143. DWORD gBlockSleep = 0;
  5144. #endif
  5145. VOID RawInputThread(
  5146. PRIT_INIT pInitData)
  5147. {
  5148. KPRIORITY Priority;
  5149. NTSTATUS Status;
  5150. UNICODE_STRING strRIT;
  5151. UINT NumberOfHandles = ID_NUMBER_HYDRA_REMOTE_HANDLES;
  5152. PTERMINAL pTerm;
  5153. PMONITOR pMonitorPrimary;
  5154. HANDLE hevtShutDown;
  5155. PKEVENT pEvents[2];
  5156. USHORT cEvents = 1;
  5157. static DWORD nLastRetryReadInput = 0;
  5158. /*
  5159. * Session 0 Console session does not need the shutdown event
  5160. */
  5161. pTerm = pInitData->pTerm;
  5162. /*
  5163. * Initialize GDI accelerators. Identify this thread as a server thread.
  5164. */
  5165. apObjects = UserAllocPoolNonPaged(NumberOfHandles * sizeof(PVOID), TAG_SYSTEM);
  5166. gWaitBlockArray = UserAllocPoolNonPagedNS(NumberOfHandles * sizeof(KWAIT_BLOCK),
  5167. TAG_SYSTEM);
  5168. if (apObjects == NULL || gWaitBlockArray == NULL) {
  5169. RIPMSG0(RIP_WARNING, "RIT failed to allocate memory");
  5170. goto Exit;
  5171. }
  5172. RtlZeroMemory(apObjects, NumberOfHandles * sizeof(PVOID));
  5173. /*
  5174. * Set the priority of the RIT to maximum allowed.
  5175. * LOW_REALTIME_PRIORITY - 1 is chosen so that the RIT
  5176. * does not block the Mm Working set trimmer thread
  5177. * in the memory starvation situation.
  5178. */
  5179. #ifdef W2K_COMPAT_PRIORITY
  5180. Priority = LOW_REALTIME_PRIORITY + 3;
  5181. #else
  5182. Priority = LOW_REALTIME_PRIORITY - 1;
  5183. #endif
  5184. ZwSetInformationThread(NtCurrentThread(),
  5185. ThreadPriority,
  5186. &Priority,
  5187. sizeof(KPRIORITY));
  5188. RtlInitUnicodeString(&strRIT, L"WinSta0_RIT");
  5189. /*
  5190. * Create an event for signalling mouse/kbd attach/detach and device-change
  5191. * notifications such as QueryRemove, RemoveCancelled etc.
  5192. */
  5193. aDeviceTemplate[DEVICE_TYPE_KEYBOARD].pkeHidChange =
  5194. apObjects[ID_HIDCHANGE] =
  5195. CreateKernelEvent(SynchronizationEvent, FALSE);
  5196. aDeviceTemplate[DEVICE_TYPE_MOUSE].pkeHidChange =
  5197. CreateKernelEvent(SynchronizationEvent, FALSE);
  5198. #ifdef GENERIC_INPUT
  5199. gpkeHidChange =
  5200. apObjects[ID_TRUEHIDCHANGE] =
  5201. aDeviceTemplate[DEVICE_TYPE_HID].pkeHidChange = CreateKernelEvent(SynchronizationEvent, FALSE);
  5202. #endif
  5203. /*
  5204. * Create an event for desktop threads to pass mouse input to RIT
  5205. */
  5206. apObjects[ID_MOUSE] = CreateKernelEvent(SynchronizationEvent, FALSE);
  5207. gpkeMouseData = apObjects[ID_MOUSE];
  5208. if (aDeviceTemplate[DEVICE_TYPE_MOUSE].pkeHidChange == NULL ||
  5209. apObjects[ID_HIDCHANGE] == NULL ||
  5210. gpkeMouseData == NULL
  5211. #ifdef GENERIC_INPUT
  5212. || gpkeHidChange == NULL
  5213. #endif
  5214. ) {
  5215. RIPMSG0(RIP_WARNING, "RIT failed to create a required input event");
  5216. goto Exit;
  5217. }
  5218. /*
  5219. * Initialize keyboard device driver.
  5220. */
  5221. EnterCrit();
  5222. InitKeyboard();
  5223. InitMice();
  5224. LeaveCrit();
  5225. Status = InitSystemThread(&strRIT);
  5226. if (!NT_SUCCESS(Status)) {
  5227. RIPMSG0(RIP_WARNING, "RIT failed InitSystemThread");
  5228. goto Exit;
  5229. }
  5230. UserAssert(gpepCSRSS != NULL);
  5231. /*
  5232. * Allow the system to read the screen
  5233. */
  5234. ((PW32PROCESS)PsGetProcessWin32Process(gpepCSRSS))->W32PF_Flags |= (W32PF_READSCREENACCESSGRANTED|W32PF_IOWINSTA);
  5235. /*
  5236. * Initialize the cursor clipping rectangle to the screen rectangle.
  5237. */
  5238. UserAssert(gpDispInfo != NULL);
  5239. grcCursorClip = gpDispInfo->rcScreen;
  5240. /*
  5241. * Initialize gpsi->ptCursor and gptCursorAsync
  5242. */
  5243. pMonitorPrimary = GetPrimaryMonitor();
  5244. UserAssert(gpsi != NULL);
  5245. gpsi->ptCursor.x = pMonitorPrimary->rcMonitor.right / 2;
  5246. gpsi->ptCursor.y = pMonitorPrimary->rcMonitor.bottom / 2;
  5247. gptCursorAsync = gpsi->ptCursor;
  5248. /*
  5249. * The hung redraw list should already be set to NULL by the compiler,
  5250. * linker & loader since it is an uninitialized global variable. Memory will
  5251. * be allocated the first time a pwnd is added to this list (hungapp.c)
  5252. */
  5253. UserAssert(gpvwplHungRedraw == NULL);
  5254. /*
  5255. * Initialize the pre-defined hotkeys
  5256. */
  5257. EnterCrit();
  5258. _RegisterHotKey(PWND_INPUTOWNER, IDHOT_WINDOWS, MOD_WIN, VK_NONE);
  5259. SetDebugHotKeys();
  5260. LeaveCrit();
  5261. /*
  5262. * Create a timer for timers.
  5263. */
  5264. gptmrMaster = UserAllocPoolNonPagedNS(sizeof(KTIMER),
  5265. TAG_SYSTEM);
  5266. if (gptmrMaster == NULL) {
  5267. RIPMSG0(RIP_WARNING, "RIT failed to create gptmrMaster");
  5268. goto Exit;
  5269. }
  5270. KeInitializeTimer(gptmrMaster);
  5271. apObjects[ID_TIMER] = gptmrMaster;
  5272. /*
  5273. * Create an event for mouse device reads to signal the desktop thread to
  5274. * move the pointer and QueueMouseEvent().
  5275. * We should do this *before* we have any devices.
  5276. */
  5277. UserAssert(gpDeviceInfoList == NULL);
  5278. if (!gbRemoteSession) {
  5279. gptmrWD = UserAllocPoolNonPagedNS(sizeof(KTIMER), TAG_SYSTEM);
  5280. if (gptmrWD == NULL) {
  5281. Status = STATUS_NO_MEMORY;
  5282. RIPMSG0(RIP_WARNING, "RemoteConnect failed to create gptmrWD");
  5283. goto Exit;
  5284. }
  5285. KeInitializeTimerEx(gptmrWD, SynchronizationTimer);
  5286. }
  5287. /*
  5288. * At this point, the WD timer must already have been initialized by RemoteConnect
  5289. */
  5290. UserAssert(gptmrWD != NULL);
  5291. apObjects[ID_WDTIMER] = gptmrWD;
  5292. if (IsRemoteConnection() ) {
  5293. BOOL fSuccess=TRUE;
  5294. fSuccess &= !!HDXDrvEscape(gpDispInfo->hDev,
  5295. ESC_SET_WD_TIMEROBJ,
  5296. (PVOID)gptmrWD,
  5297. sizeof(gptmrWD));
  5298. if (!fSuccess) {
  5299. Status = STATUS_UNSUCCESSFUL;
  5300. RIPMSG0(RIP_WARNING, "RemoteConnect failed to pass gptmrWD to display driver");
  5301. goto Exit;
  5302. }
  5303. }
  5304. if (IsRemoteConnection()) {
  5305. UNICODE_STRING ustrName;
  5306. BOOL fSuccess = TRUE;
  5307. RtlInitUnicodeString(&ustrName, NULL);
  5308. /*
  5309. * Pass a pointer to the timer to the WD via the display driver
  5310. */
  5311. EnterCrit();
  5312. fSuccess &= !!CreateDeviceInfo(DEVICE_TYPE_MOUSE, &ustrName, 0);
  5313. fSuccess &= !!CreateDeviceInfo(DEVICE_TYPE_KEYBOARD, &ustrName, 0);
  5314. LeaveCrit();
  5315. if (!fSuccess) {
  5316. RIPMSG0(RIP_WARNING,
  5317. "RIT failed HDXDrvEscape or the creation of input devices");
  5318. goto Exit;
  5319. }
  5320. } else {
  5321. EnterCrit();
  5322. /*
  5323. * Register for Plug and Play devices.
  5324. * If any PnP devices are already attached, these will be opened and
  5325. * we will start reading them at this time.
  5326. */
  5327. xxxRegisterForDeviceClassNotifications();
  5328. LeaveCrit();
  5329. }
  5330. if (gbRemoteSession) {
  5331. WCHAR szName[MAX_SESSION_PATH];
  5332. UNICODE_STRING ustrName;
  5333. OBJECT_ATTRIBUTES obja;
  5334. /*
  5335. * Create the shutdown event. This event will be signaled
  5336. * from W32WinStationTerminate.
  5337. * This is a named event opend by CSR to signal that win32k should
  5338. * go away. It's used in ntuser\server\api.c
  5339. */
  5340. swprintf(szName, L"\\Sessions\\%ld\\BaseNamedObjects\\EventShutDownCSRSS",
  5341. gSessionId);
  5342. RtlInitUnicodeString(&ustrName, szName);
  5343. InitializeObjectAttributes(&obja,
  5344. &ustrName,
  5345. OBJ_CASE_INSENSITIVE,
  5346. NULL,
  5347. NULL);
  5348. Status = ZwCreateEvent(&hevtShutDown,
  5349. EVENT_ALL_ACCESS,
  5350. &obja,
  5351. SynchronizationEvent,
  5352. FALSE);
  5353. if (!NT_SUCCESS(Status)) {
  5354. RIPMSG0(RIP_WARNING, "RIT failed to create EventShutDownCSRSS");
  5355. goto Exit;
  5356. }
  5357. ObReferenceObjectByHandle(hevtShutDown,
  5358. EVENT_ALL_ACCESS,
  5359. *ExEventObjectType,
  5360. KernelMode,
  5361. &apObjects[ID_SHUTDOWN],
  5362. NULL);
  5363. pEvents[1] = apObjects[ID_SHUTDOWN];
  5364. cEvents++;
  5365. } else {
  5366. hevtShutDown = NULL;
  5367. Status = PoRequestShutdownEvent(&apObjects[ID_SHUTDOWN]);
  5368. if (!NT_SUCCESS(Status)) {
  5369. RIPMSG0(RIP_WARNING, "RIT failed to get shutdown event");
  5370. goto Exit;
  5371. }
  5372. }
  5373. /*
  5374. * Get the rit-thread.
  5375. */
  5376. gptiRit = PtiCurrentShared();
  5377. HYDRA_HINT(HH_RITCREATED);
  5378. /*
  5379. * Don't allow this thread to get involved with journal synchronization.
  5380. */
  5381. gptiRit->TIF_flags |= TIF_DONTJOURNALATTACH;
  5382. /*
  5383. * Also wait on our input event so the cool switch window can
  5384. * receive messages.
  5385. */
  5386. apObjects[ID_INPUT] = gptiRit->pEventQueueServer;
  5387. /*
  5388. * Signal that the rit has been initialized
  5389. */
  5390. KeSetEvent(pInitData->pRitReadyEvent, EVENT_INCREMENT, FALSE);
  5391. pEvents[0] = pTerm->pEventInputReady;
  5392. /*
  5393. * Wait until the first desktop is created.
  5394. */
  5395. ObReferenceObjectByPointer(pEvents[0],
  5396. EVENT_ALL_ACCESS,
  5397. *ExEventObjectType,
  5398. KernelMode);
  5399. Status = KeWaitForMultipleObjects(cEvents,
  5400. pEvents,
  5401. WaitAny,
  5402. WrUserRequest,
  5403. KernelMode,
  5404. FALSE,
  5405. NULL,
  5406. NULL);
  5407. ObDereferenceObject(pEvents[0]);
  5408. if (Status == WAIT_OBJECT_0 + 1) {
  5409. KeSetEvent(pEvents[1], EVENT_INCREMENT, FALSE);
  5410. InitiateWin32kCleanup();
  5411. ObDereferenceObject(pEvents[1]);
  5412. if (hevtShutDown) {
  5413. ZwClose(hevtShutDown);
  5414. }
  5415. return;
  5416. }
  5417. /*
  5418. * Switch to the first desktop if no switch has been
  5419. * performed.
  5420. */
  5421. EnterCrit();
  5422. if (gptiRit->rpdesk == NULL) {
  5423. UserVerify(xxxSwitchDesktop(gptiRit->pwinsta, gptiRit->pwinsta->rpdeskList, 0));
  5424. }
  5425. /*
  5426. * The io desktop thread is supposed to be created at this point.
  5427. * The xxxSwitchDesktop call is expected to set the io desktop thread to run in grpdeskritinput
  5428. */
  5429. if ((pTerm->ptiDesktop == NULL) || (pTerm->ptiDesktop->rpdesk != grpdeskRitInput)) {
  5430. FRE_RIPMSG0(RIP_ERROR, "RawInputThread: Desktop thread not running on grpdeskRitInput");
  5431. }
  5432. /*
  5433. * Create a timer for hung app detection/redrawing.
  5434. */
  5435. StartTimers();
  5436. LeaveCrit();
  5437. /*
  5438. * Go into a wait loop so we can process input events and APCs as
  5439. * they occur.
  5440. */
  5441. while (TRUE) {
  5442. CheckCritOut();
  5443. Status = KeWaitForMultipleObjects(NumberOfHandles,
  5444. apObjects,
  5445. WaitAny,
  5446. WrUserRequest,
  5447. KernelMode,
  5448. TRUE,
  5449. NULL,
  5450. gWaitBlockArray);
  5451. UserAssert(NT_SUCCESS(Status));
  5452. if (gdwUpdateKeyboard != 0) {
  5453. /*
  5454. * Here's our opportunity to process pending IOCTLs for the kbds:
  5455. * These are asynchronous IOCTLS, so be sure any buffers passed
  5456. * in to ZwDeviceIoControlFile are not in the stack!
  5457. * Using gdwUpdateKeyboard to tell the RIT to issue these IOCTLS
  5458. * renders the action asynchronous (delayed until next apObjects
  5459. * event), but the IOCTL was asynch anyway
  5460. */
  5461. PDEVICEINFO pDeviceInfo;
  5462. EnterDeviceInfoListCrit();
  5463. for (pDeviceInfo = gpDeviceInfoList; pDeviceInfo; pDeviceInfo = pDeviceInfo->pNext) {
  5464. if ((pDeviceInfo->type == DEVICE_TYPE_KEYBOARD) && (pDeviceInfo->handle)) {
  5465. if (gdwUpdateKeyboard & UPDATE_KBD_TYPEMATIC) {
  5466. ZwDeviceIoControlFile(pDeviceInfo->handle, NULL, NULL, NULL,
  5467. &giosbKbdControl, IOCTL_KEYBOARD_SET_TYPEMATIC,
  5468. (PVOID)&gktp, sizeof(gktp), NULL, 0);
  5469. }
  5470. if (gdwUpdateKeyboard & UPDATE_KBD_LEDS) {
  5471. ZwDeviceIoControlFile(pDeviceInfo->handle, NULL, NULL, NULL,
  5472. &giosbKbdControl, IOCTL_KEYBOARD_SET_INDICATORS,
  5473. (PVOID)&gklp, sizeof(gklp), NULL, 0);
  5474. }
  5475. }
  5476. }
  5477. LeaveDeviceInfoListCrit();
  5478. if ((gdwUpdateKeyboard & UPDATE_KBD_LEDS) && gfRemotingConsole) {
  5479. ZwDeviceIoControlFile(ghConsoleShadowKeyboardChannel, NULL, NULL, NULL,
  5480. &giosbKbdControl, IOCTL_KEYBOARD_SET_INDICATORS,
  5481. (PVOID)&gklp, sizeof(gklp), NULL, 0);
  5482. }
  5483. gdwUpdateKeyboard &= ~(UPDATE_KBD_TYPEMATIC | UPDATE_KBD_LEDS);
  5484. }
  5485. if (Status == ID_MOUSE) {
  5486. /*
  5487. * A desktop thread got some Mouse input for us. Process it.
  5488. */
  5489. ProcessQueuedMouseEvents();
  5490. } else if (Status == ID_HIDCHANGE) {
  5491. TAGMSG0(DBGTAG_PNP | RIP_THERESMORE, "RIT wakes for HID Change");
  5492. EnterCrit();
  5493. ProcessDeviceChanges(DEVICE_TYPE_KEYBOARD);
  5494. LeaveCrit();
  5495. }
  5496. #ifdef GENERIC_INPUT
  5497. else if (Status == ID_TRUEHIDCHANGE) {
  5498. TAGMSG0(DBGTAG_PNP | RIP_THERESMORE, "RIT wakes for True HID Change");
  5499. EnterCrit();
  5500. ProcessDeviceChanges(DEVICE_TYPE_HID);
  5501. LeaveCrit();
  5502. }
  5503. #endif
  5504. else if (Status == ID_SHUTDOWN) {
  5505. InitiateWin32kCleanup();
  5506. if(gbRemoteSession) {
  5507. ObDereferenceObject(apObjects[ID_SHUTDOWN]);
  5508. }
  5509. if (hevtShutDown) {
  5510. ZwClose(hevtShutDown);
  5511. }
  5512. break;
  5513. } else if (Status == ID_WDTIMER) {
  5514. //LARGE_INTEGER liTemp;
  5515. EnterCrit();
  5516. /*
  5517. * Call the TShare display driver to flush the frame buffer
  5518. */
  5519. if (IsRemoteConnection()) {
  5520. if (!HDXDrvEscape(gpDispInfo->hDev, ESC_TIMEROBJ_SIGNALED, NULL, 0)) {
  5521. UserAssert(FALSE);
  5522. }
  5523. } else {
  5524. if (gfRemotingConsole && gConsoleShadowhDev != NULL) {
  5525. ASSERT(gConsoleShadowhDev != NULL);
  5526. if (!HDXDrvEscape(gConsoleShadowhDev, ESC_TIMEROBJ_SIGNALED, NULL, 0)) {
  5527. UserAssert(FALSE);
  5528. }
  5529. }
  5530. }
  5531. LeaveCrit();
  5532. } else {
  5533. /*
  5534. * If the master timer has expired, then process the timer
  5535. * list. Otherwise, an APC caused the raw input thread to be
  5536. * awakened.
  5537. */
  5538. if (Status == ID_TIMER) {
  5539. TimersProc();
  5540. /*
  5541. * If an input degvice read failed due to insufficient resources,
  5542. * we retry by signalling the proper thread: ProcessDeviceChanges
  5543. * will call RetryReadInput().
  5544. */
  5545. if (gnRetryReadInput != nLastRetryReadInput) {
  5546. nLastRetryReadInput = gnRetryReadInput;
  5547. KeSetEvent(aDeviceTemplate[DEVICE_TYPE_MOUSE].pkeHidChange, EVENT_INCREMENT, FALSE);
  5548. KeSetEvent(aDeviceTemplate[DEVICE_TYPE_KEYBOARD].pkeHidChange, EVENT_INCREMENT, FALSE);
  5549. }
  5550. }
  5551. #if DBG
  5552. /*
  5553. * In the debugger set gBlockSleep to n:
  5554. * The RIT will sleep n millicseconds, then n timer ticks later
  5555. * will sleep n milliseconds again.
  5556. */
  5557. if (gBlockDelay) {
  5558. gBlockDelay--;
  5559. } else if ((gBlockDelay == 0) && (gBlockSleep != 0)) {
  5560. UserSleep(gBlockSleep);
  5561. gBlockDelay = 100 * gBlockSleep;
  5562. }
  5563. #endif
  5564. /*
  5565. * if in cool task switcher window, dispose of the messages
  5566. * on the queue
  5567. */
  5568. if (gspwndAltTab != NULL) {
  5569. EnterCrit();
  5570. xxxReceiveMessages(gptiRit);
  5571. LeaveCrit();
  5572. }
  5573. }
  5574. }
  5575. return;
  5576. Exit:
  5577. UserAssert(gptiRit == NULL);
  5578. /*
  5579. * Signal that the rit has been initialized
  5580. */
  5581. KeSetEvent(pInitData->pRitReadyEvent, EVENT_INCREMENT, FALSE);
  5582. RIPMSG0(RIP_WARNING, "RIT initialization failure");
  5583. }