Don't return characters is key is up
[reactos.git] / reactos / subsys / win32k / ntuser / keyboard.c
1 /*
2 * ReactOS W32 Subsystem
3 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 ReactOS Team
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19 /*
20 * COPYRIGHT: See COPYING in the top level directory
21 * PROJECT: ReactOS kernel
22 * PURPOSE: Messages
23 * FILE: subsys/win32k/ntuser/keyboard.c
24 * PROGRAMER: Casper S. Hornstrup (chorns@users.sourceforge.net)
25 * REVISION HISTORY:
26 * 06-06-2001 CSH Created
27 */
28
29 /* INCLUDES ******************************************************************/
30
31 #include <w32k.h>
32
33 #define NDEBUG
34 #include <debug.h>
35
36 /* Directory to load key layouts from */
37 #define SYSTEMROOT_DIR L"\\SystemRoot\\System32\\"
38 /* Lock modifiers */
39 #define CAPITAL_BIT 0x80000000
40 #define NUMLOCK_BIT 0x40000000
41 #define MOD_BITS_MASK 0x3fffffff
42 #define MOD_KCTRL 0x02
43 /* Key States */
44 #define KS_DOWN_MASK 0xc0
45 #define KS_DOWN_BIT 0x80
46 #define KS_LOCK_BIT 0x01
47 /* lParam bits */
48 #define LP_EXT_BIT (1<<24)
49 /* From kbdxx.c -- Key changes with numlock */
50 #define KNUMP 0x400
51
52 /* Lock the keyboard state to prevent unusual concurrent access */
53 FAST_MUTEX QueueStateLock;
54
55 BYTE QueueKeyStateTable[256];
56
57 #define IntLockQueueState \
58 ExAcquireFastMutex(&QueueStateLock)
59
60 #define IntUnLockQueueState \
61 ExReleaseFastMutex(&QueueStateLock)
62
63 /* FUNCTIONS *****************************************************************/
64
65 /* Initialization -- Right now, just zero the key state and init the lock */
66 NTSTATUS FASTCALL InitKeyboardImpl(VOID) {
67 ExInitializeFastMutex(&QueueStateLock);
68 RtlZeroMemory(&QueueKeyStateTable,0x100);
69 return STATUS_SUCCESS;
70 }
71
72 /*** Statics used by TranslateMessage ***/
73
74 /*** Shift state code was out of hand, sorry. --- arty */
75
76 static UINT DontDistinguishShifts( UINT ret ) {
77 if( ret == VK_LSHIFT || ret == VK_RSHIFT ) ret = VK_LSHIFT;
78 if( ret == VK_LCONTROL || ret == VK_RCONTROL ) ret = VK_LCONTROL;
79 if( ret == VK_LMENU || ret == VK_RMENU ) ret = VK_LMENU;
80 return ret;
81 }
82
83 static VOID STDCALL SetKeyState(DWORD key, DWORD vk, DWORD ext, BOOL down) {
84 ASSERT(vk <= 0xff);
85
86 /* Special handling for toggles like numpad and caps lock */
87 if (vk == VK_CAPITAL || vk == VK_NUMLOCK) {
88 if (down) QueueKeyStateTable[vk] ^= KS_LOCK_BIT;
89 }
90
91 if (ext && vk == VK_LSHIFT)
92 vk = VK_RSHIFT;
93 if (ext && vk == VK_LCONTROL)
94 vk = VK_RCONTROL;
95 if (ext && vk == VK_LMENU)
96 vk = VK_RMENU;
97
98 if (down)
99 QueueKeyStateTable[vk] |= KS_DOWN_BIT;
100 else
101 QueueKeyStateTable[vk] &= ~KS_DOWN_MASK;
102
103 if (vk == VK_LSHIFT || vk == VK_RSHIFT) {
104 if ((QueueKeyStateTable[VK_LSHIFT] & KS_DOWN_BIT) ||
105 (QueueKeyStateTable[VK_RSHIFT] & KS_DOWN_BIT)) {
106 QueueKeyStateTable[VK_SHIFT] |= KS_DOWN_BIT;
107 } else {
108 QueueKeyStateTable[VK_SHIFT] &= ~KS_DOWN_MASK;
109 }
110 }
111
112 if (vk == VK_LCONTROL || vk == VK_RCONTROL) {
113 if ((QueueKeyStateTable[VK_LCONTROL] & KS_DOWN_BIT) ||
114 (QueueKeyStateTable[VK_RCONTROL] & KS_DOWN_BIT)) {
115 QueueKeyStateTable[VK_CONTROL] |= KS_DOWN_BIT;
116 } else {
117 QueueKeyStateTable[VK_CONTROL] &= ~KS_DOWN_MASK;
118 }
119 }
120
121 if (vk == VK_LMENU || vk == VK_RMENU) {
122 if ((QueueKeyStateTable[VK_LMENU] & KS_DOWN_BIT) ||
123 (QueueKeyStateTable[VK_RMENU] & KS_DOWN_BIT)) {
124 QueueKeyStateTable[VK_MENU] |= KS_DOWN_BIT;
125 } else {
126 QueueKeyStateTable[VK_MENU] &= ~KS_DOWN_MASK;
127 }
128 }
129 }
130
131 VOID DumpKeyState( PBYTE KeyState ) {
132 int i;
133
134 DbgPrint( "KeyState { " );
135 for( i = 0; i < 0x100; i++ ) {
136 if( KeyState[i] ) DbgPrint( "%02x(%02x) ", i, KeyState[i] );
137 }
138 DbgPrint( "};\n" );
139 }
140
141 static BYTE KeysSet( PKBDTABLES pkKT, PBYTE KeyState,
142 int FakeModLeft, int FakeModRight ) {
143 if( !KeyState || !pkKT ) return 0;
144
145 /* Search special codes first */
146 if( FakeModLeft && KeyState[FakeModLeft] )
147 return KeyState[FakeModLeft];
148 else if( FakeModRight && KeyState[FakeModRight] )
149 return KeyState[FakeModRight];
150
151 return 0;
152 }
153
154 /* Search the keyboard layout modifiers table for the shift bit. I don't
155 * want to count on the shift bit not moving, because it can be specified
156 * in the layout */
157
158 static DWORD FASTCALL GetShiftBit( PKBDTABLES pkKT, DWORD Vk ) {
159 int i;
160
161 for( i = 0; pkKT->pCharModifiers->pVkToBit[i].Vk; i++ )
162 if( pkKT->pCharModifiers->pVkToBit[i].Vk == Vk )
163 return pkKT->pCharModifiers->pVkToBit[i].ModBits;
164
165 return 0;
166 }
167
168 static DWORD ModBits( PKBDTABLES pkKT, PBYTE KeyState ) {
169 DWORD ModBits = 0;
170
171 if( !KeyState ) return 0;
172
173 /* DumpKeyState( KeyState ); */
174
175 if (KeysSet( pkKT, KeyState, VK_LSHIFT, VK_RSHIFT ) &
176 KS_DOWN_BIT)
177 ModBits |= GetShiftBit( pkKT, VK_SHIFT );
178
179 if (KeysSet( pkKT, KeyState, VK_LCONTROL, VK_RCONTROL ) &
180 KS_DOWN_BIT )
181 ModBits |= GetShiftBit( pkKT, VK_CONTROL );
182
183 if (KeysSet( pkKT, KeyState, VK_LMENU, VK_RMENU ) &
184 KS_DOWN_BIT )
185 ModBits |= GetShiftBit( pkKT, VK_MENU );
186
187 /* Handle Alt+Gr */
188 if (KeysSet( pkKT, KeyState, VK_RMENU, 0 ) &
189 KS_DOWN_BIT )
190 ModBits |= GetShiftBit( pkKT, VK_CONTROL );
191
192 /* Deal with VK_CAPITAL */
193 if (KeysSet( pkKT, KeyState, VK_CAPITAL, 0 ) & KS_LOCK_BIT)
194 {
195 ModBits |= CAPITAL_BIT;
196 }
197
198 /* Deal with VK_NUMLOCK */
199 if (KeysSet( pkKT, KeyState, VK_NUMLOCK, 0 ) & KS_LOCK_BIT)
200 {
201 ModBits |= NUMLOCK_BIT;
202 }
203
204 DPRINT( "Current Mod Bits: %x\n", ModBits );
205
206 return ModBits;
207 }
208
209 static BOOL TryToTranslateChar(WORD wVirtKey,
210 DWORD ModBits,
211 PBOOL pbDead,
212 PBOOL pbLigature,
213 PWCHAR pwcTranslatedChar,
214 PKBDTABLES keyLayout )
215 {
216 PVK_TO_WCHAR_TABLE vtwTbl;
217 PVK_TO_WCHARS10 vkPtr;
218 size_t size_this_entry;
219 int nMod, shift;
220 DWORD CapsMod = 0, CapsState = 0;
221
222 CapsState = ModBits & ~MOD_BITS_MASK;
223 ModBits = ModBits & MOD_BITS_MASK;
224
225 DPRINT ( "TryToTranslate: %04x %x\n", wVirtKey, ModBits );
226
227 if (ModBits > keyLayout->pCharModifiers->wMaxModBits)
228 {
229 return FALSE;
230 }
231 shift = keyLayout->pCharModifiers->ModNumber[ModBits];
232
233 for (nMod = 0; keyLayout->pVkToWcharTable[nMod].nModifications; nMod++)
234 {
235 vtwTbl = &keyLayout->pVkToWcharTable[nMod];
236 size_this_entry = vtwTbl->cbSize;
237 vkPtr = (PVK_TO_WCHARS10)((BYTE *)vtwTbl->pVkToWchars);
238 while(vkPtr->VirtualKey)
239 {
240 if( wVirtKey == (vkPtr->VirtualKey & 0xff) )
241 {
242 CapsMod =
243 shift | ((CapsState & CAPITAL_BIT) ? vkPtr->Attributes : 0);
244
245 if( CapsMod > keyLayout->pVkToWcharTable[nMod].nModifications ) {
246 DWORD MaxBit = 1;
247 while( MaxBit <
248 keyLayout->pVkToWcharTable[nMod].nModifications )
249 MaxBit <<= 1;
250
251 CapsMod &= MaxBit - 1; /* Guarantee that CapsMod lies
252 in bounds. */
253 }
254
255 *pbDead = vkPtr->wch[CapsMod] == WCH_DEAD;
256 *pbLigature = vkPtr->wch[CapsMod] == WCH_LGTR;
257 *pwcTranslatedChar = vkPtr->wch[CapsMod];
258
259 DPRINT("%d %04x: CapsMod %08x CapsState %08x shift %08x Char %04x\n",
260 nMod, wVirtKey,
261 CapsMod, CapsState, shift, *pwcTranslatedChar);
262
263 if( *pbDead )
264 {
265 vkPtr = (PVK_TO_WCHARS10)(((BYTE *)vkPtr) + size_this_entry);
266 if( vkPtr->VirtualKey != 0xff )
267 {
268 DPRINT( "Found dead key with no trailer in the table.\n" );
269 DPRINT( "VK: %04x, ADDR: %08x\n", wVirtKey, (int)vkPtr );
270 return FALSE;
271 }
272 *pwcTranslatedChar = vkPtr->wch[shift];
273 }
274 return TRUE;
275 }
276 vkPtr = (PVK_TO_WCHARS10)(((BYTE *)vkPtr) + size_this_entry);
277 }
278 }
279 return FALSE;
280 }
281
282 static
283 int STDCALL
284 ToUnicodeInner(UINT wVirtKey,
285 UINT wScanCode,
286 PBYTE lpKeyState,
287 LPWSTR pwszBuff,
288 int cchBuff,
289 UINT wFlags,
290 PKBDTABLES pkKT)
291 {
292 WCHAR wcTranslatedChar;
293 BOOL bDead;
294 BOOL bLigature;
295
296 if( !pkKT ) return 0;
297
298 if( TryToTranslateChar( wVirtKey,
299 ModBits( pkKT, lpKeyState ),
300 &bDead,
301 &bLigature,
302 &wcTranslatedChar,
303 pkKT ) )
304 {
305 if( bLigature )
306 {
307 DPRINT("Not handling ligature (yet)\n" );
308 return 0;
309 }
310
311 if( cchBuff > 0 ) pwszBuff[0] = wcTranslatedChar;
312
313 return bDead ? -1 : 1;
314 }
315
316 return 0;
317 }
318
319 DWORD
320 STDCALL
321 NtUserGetKeyState(
322 DWORD key)
323 {
324 DWORD ret = 0;
325
326 IntLockQueueState;
327 if( key < 0x100 ) {
328 ret = ((DWORD)(QueueKeyStateTable[key] & KS_DOWN_BIT) << 8 ) |
329 (QueueKeyStateTable[key] & KS_LOCK_BIT);
330 }
331 IntUnLockQueueState;
332 return ret;
333 }
334
335 int STDCALL ToUnicodeEx( UINT wVirtKey,
336 UINT wScanCode,
337 PBYTE lpKeyState,
338 LPWSTR pwszBuff,
339 int cchBuff,
340 UINT wFlags,
341 HKL dwhkl ) {
342 int ToUnicodeResult = 0;
343
344 if (0 == (lpKeyState[wVirtKey] & KS_DOWN_BIT))
345 {
346 ToUnicodeResult = 0;
347 }
348 else
349 {
350 IntLockQueueState;
351 ToUnicodeResult = ToUnicodeInner( wVirtKey,
352 wScanCode,
353 lpKeyState,
354 pwszBuff,
355 cchBuff,
356 wFlags,
357 PsGetWin32Thread() ?
358 PsGetWin32Thread()->KeyboardLayout : 0 );
359 IntUnLockQueueState;
360 }
361
362 return ToUnicodeResult;
363 }
364
365 int STDCALL ToUnicode( UINT wVirtKey,
366 UINT wScanCode,
367 PBYTE lpKeyState,
368 LPWSTR pwszBuff,
369 int cchBuff,
370 UINT wFlags ) {
371 return ToUnicodeEx( wVirtKey,
372 wScanCode,
373 QueueKeyStateTable,
374 pwszBuff,
375 cchBuff,
376 wFlags,
377 0 );
378 }
379
380 /*
381 * Utility to copy and append two unicode strings.
382 *
383 * IN OUT PUNICODE_STRING ResultFirst -> First string and result
384 * IN PUNICODE_STRING Second -> Second string to append
385 * IN BOOL Deallocate -> TRUE: Deallocate First string before
386 * overwriting.
387 *
388 * Returns NTSTATUS.
389 */
390
391 NTSTATUS NTAPI AppendUnicodeString(PUNICODE_STRING ResultFirst,
392 PUNICODE_STRING Second,
393 BOOL Deallocate) {
394 NTSTATUS Status;
395 PWSTR new_string =
396 ExAllocatePoolWithTag(PagedPool,
397 (ResultFirst->Length + Second->Length + sizeof(WCHAR)),
398 TAG_STRING);
399 if( !new_string ) {
400 return STATUS_NO_MEMORY;
401 }
402 memcpy( new_string, ResultFirst->Buffer,
403 ResultFirst->Length );
404 memcpy( new_string + ResultFirst->Length / sizeof(WCHAR),
405 Second->Buffer,
406 Second->Length );
407 if( Deallocate ) RtlFreeUnicodeString(ResultFirst);
408 ResultFirst->Length += Second->Length;
409 ResultFirst->MaximumLength = ResultFirst->Length;
410 new_string[ResultFirst->Length / sizeof(WCHAR)] = 0;
411 Status = RtlCreateUnicodeString(ResultFirst,new_string) ?
412 STATUS_SUCCESS : STATUS_NO_MEMORY;
413 ExFreePool(new_string);
414 return Status;
415 }
416
417 /*
418 * Utility function to read a value from the registry more easily.
419 *
420 * IN PUNICODE_STRING KeyName -> Name of key to open
421 * IN PUNICODE_STRING ValueName -> Name of value to open
422 * OUT PUNICODE_STRING ReturnedValue -> String contained in registry
423 *
424 * Returns NTSTATUS
425 */
426
427 static NTSTATUS NTAPI ReadRegistryValue( PUNICODE_STRING KeyName,
428 PUNICODE_STRING ValueName,
429 PUNICODE_STRING ReturnedValue ) {
430 NTSTATUS Status;
431 HANDLE KeyHandle;
432 OBJECT_ATTRIBUTES KeyAttributes;
433 PKEY_VALUE_PARTIAL_INFORMATION KeyValuePartialInfo;
434 ULONG Length = 0;
435 ULONG ResLength = 0;
436 UNICODE_STRING Temp;
437
438 InitializeObjectAttributes(&KeyAttributes, KeyName, OBJ_CASE_INSENSITIVE,
439 NULL, NULL);
440 Status = ZwOpenKey(&KeyHandle, KEY_ALL_ACCESS, &KeyAttributes);
441 if( !NT_SUCCESS(Status) ) {
442 return Status;
443 }
444
445 Status = ZwQueryValueKey(KeyHandle, ValueName, KeyValuePartialInformation,
446 0,
447 0,
448 &ResLength);
449
450 if( Status != STATUS_BUFFER_TOO_SMALL ) {
451 NtClose(KeyHandle);
452 return Status;
453 }
454
455 ResLength += sizeof( *KeyValuePartialInfo );
456 KeyValuePartialInfo =
457 ExAllocatePoolWithTag(PagedPool, ResLength, TAG_STRING);
458 Length = ResLength;
459
460 if( !KeyValuePartialInfo ) {
461 NtClose(KeyHandle);
462 return STATUS_NO_MEMORY;
463 }
464
465 Status = ZwQueryValueKey(KeyHandle, ValueName, KeyValuePartialInformation,
466 (PVOID)KeyValuePartialInfo,
467 Length,
468 &ResLength);
469
470 if( !NT_SUCCESS(Status) ) {
471 NtClose(KeyHandle);
472 ExFreePool(KeyValuePartialInfo);
473 return Status;
474 }
475
476 Temp.Length = Temp.MaximumLength = KeyValuePartialInfo->DataLength;
477 Temp.Buffer = (PWCHAR)KeyValuePartialInfo->Data;
478
479 /* At this point, KeyValuePartialInfo->Data contains the key data */
480 RtlInitUnicodeString(ReturnedValue,L"");
481 AppendUnicodeString(ReturnedValue,&Temp,FALSE);
482
483 ExFreePool(KeyValuePartialInfo);
484 NtClose(KeyHandle);
485
486 return Status;
487 }
488
489 typedef PVOID (*KbdLayerDescriptor)(VOID);
490 NTSTATUS STDCALL LdrGetProcedureAddress(PVOID module,
491 PANSI_STRING import_name,
492 DWORD flags,
493 PVOID *func_addr);
494
495 void InitKbdLayout( PVOID *pkKeyboardLayout )
496 {
497 WCHAR LocaleBuffer[16];
498 UNICODE_STRING LayoutKeyName;
499 UNICODE_STRING LayoutValueName;
500 UNICODE_STRING DefaultLocale;
501 UNICODE_STRING LayoutFile;
502 UNICODE_STRING FullLayoutPath;
503 LCID LocaleId;
504 PWCHAR KeyboardLayoutWSTR;
505 HMODULE kbModule = 0;
506 NTSTATUS Status;
507 ANSI_STRING kbdProcedureName;
508 KbdLayerDescriptor layerDescGetFn;
509
510 #define XX_STATUS(x) if (!NT_SUCCESS(Status = (x))) continue;
511
512 do {
513 Status = ZwQueryDefaultLocale(FALSE, &LocaleId);
514 if (!NT_SUCCESS(Status))
515 {
516 DPRINT1("Could not get default locale (%08lx).\n", Status);
517 }
518 else
519 {
520 DPRINT("DefaultLocale = %lx\n", LocaleId);
521 swprintf(LocaleBuffer, L"%08lx", LocaleId);
522 DPRINT("DefaultLocale = %S\n", LocaleBuffer);
523 RtlInitUnicodeString(&DefaultLocale, LocaleBuffer);
524
525 RtlInitUnicodeString(&LayoutKeyName,
526 L"\\REGISTRY\\Machine\\SYSTEM\\CurrentControlSet"
527 L"\\Control\\KeyboardLayouts\\");
528
529 AppendUnicodeString(&LayoutKeyName,&DefaultLocale,FALSE);
530
531 RtlInitUnicodeString(&LayoutValueName,L"Layout File");
532
533 Status = ReadRegistryValue(&LayoutKeyName,&LayoutValueName,&LayoutFile);
534 RtlInitUnicodeString(&FullLayoutPath,SYSTEMROOT_DIR);
535
536 if( !NT_SUCCESS(Status) ) {
537 DPRINT1("Got default locale but not layout file. (%08x)\n",
538 Status);
539 RtlFreeUnicodeString(&LayoutFile);
540 } else {
541 DPRINT("Read registry and got %wZ\n", &LayoutFile);
542
543 RtlFreeUnicodeString(&LayoutKeyName);
544
545 AppendUnicodeString(&FullLayoutPath,&LayoutFile,FALSE);
546
547 DPRINT("Loading Keyboard DLL %wZ\n", &FullLayoutPath);
548
549 RtlFreeUnicodeString(&LayoutFile);
550
551 KeyboardLayoutWSTR =
552 ExAllocatePoolWithTag(PagedPool,
553 FullLayoutPath.Length + sizeof(WCHAR),
554 TAG_STRING);
555
556 if( !KeyboardLayoutWSTR ) {
557 DPRINT1("Couldn't allocate a string for the keyboard layout name.\n");
558 RtlFreeUnicodeString(&FullLayoutPath);
559 return;
560 }
561 memcpy(KeyboardLayoutWSTR,FullLayoutPath.Buffer,
562 FullLayoutPath.Length + sizeof(WCHAR));
563 KeyboardLayoutWSTR[FullLayoutPath.Length / sizeof(WCHAR)] = 0;
564
565 kbModule = EngLoadImage(KeyboardLayoutWSTR);
566 DPRINT( "Load Keyboard Layout: %S\n", KeyboardLayoutWSTR );
567
568 if( !kbModule )
569 DPRINT1( "Load Keyboard Layout: No %wZ\n", &FullLayoutPath );
570 }
571
572 RtlFreeUnicodeString(&FullLayoutPath);
573 }
574
575 if( !kbModule )
576 {
577 DPRINT1("Trying to load US Keyboard Layout\n");
578 kbModule = EngLoadImage(L"\\SystemRoot\\system32\\kbdus.dll");
579
580 if (!kbModule)
581 {
582 DPRINT1("Failed to load any Keyboard Layout\n");
583 return;
584 }
585 }
586
587 RtlInitAnsiString( &kbdProcedureName, "KbdLayerDescriptor" );
588
589 LdrGetProcedureAddress((PVOID)kbModule,
590 &kbdProcedureName,
591 0,
592 (PVOID*)&layerDescGetFn);
593
594 if( layerDescGetFn ) {
595 *pkKeyboardLayout = layerDescGetFn();
596 }
597 } while (FALSE);
598
599 if( !*pkKeyboardLayout ) {
600 DPRINT1("Failed to load the keyboard layout.\n");
601 }
602
603 #undef XX_STATUS
604 }
605
606 PKBDTABLES W32kGetDefaultKeyLayout() {
607 PKBDTABLES pkKeyboardLayout = 0;
608 InitKbdLayout( (PVOID) &pkKeyboardLayout );
609 return pkKeyboardLayout;
610 }
611
612 BOOL FASTCALL
613 IntTranslateKbdMessage(LPMSG lpMsg,
614 HKL dwhkl)
615 {
616 static INT dead_char = 0;
617 LONG UState = 0;
618 WCHAR wp[2] = { 0 };
619 MSG NewMsg = { 0 };
620 PKBDTABLES keyLayout;
621 BOOL Result = FALSE;
622 DWORD ScanCode = 0;
623
624
625 keyLayout = PsGetWin32Thread()->KeyboardLayout;
626 if( !keyLayout )
627 return FALSE;
628
629 if (lpMsg->message != WM_KEYDOWN && lpMsg->message != WM_SYSKEYDOWN)
630 return FALSE;
631
632 ScanCode = (lpMsg->lParam >> 16) & 0xff;
633
634 IntLockQueueState;
635
636 UState = ToUnicodeInner(lpMsg->wParam, HIWORD(lpMsg->lParam) & 0xff,
637 QueueKeyStateTable, wp, 2, 0,
638 keyLayout );
639
640 if (UState == 1)
641 {
642 NewMsg.message = (lpMsg->message == WM_KEYDOWN) ? WM_CHAR : WM_SYSCHAR;
643 if (dead_char)
644 {
645 ULONG i;
646 WCHAR first, second;
647 DPRINT("PREVIOUS DEAD CHAR: %c\n", dead_char);
648
649 for( i = 0; keyLayout->pDeadKey[i].dwBoth; i++ )
650 {
651 first = keyLayout->pDeadKey[i].dwBoth >> 16;
652 second = keyLayout->pDeadKey[i].dwBoth;
653 if (first == dead_char && second == wp[0])
654 {
655 wp[0] = keyLayout->pDeadKey[i].wchComposed;
656 dead_char = 0;
657 break;
658 }
659 }
660
661 DPRINT("FINAL CHAR: %c\n", wp[0]);
662 }
663 if (dead_char)
664 {
665 NewMsg.hwnd = lpMsg->hwnd;
666 NewMsg.wParam = dead_char;
667 NewMsg.lParam = lpMsg->lParam;
668 dead_char = 0;
669 MsqPostMessage(PsGetWin32Thread()->MessageQueue, &NewMsg, FALSE, QS_KEY);
670 }
671
672 NewMsg.hwnd = lpMsg->hwnd;
673 NewMsg.wParam = wp[0];
674 NewMsg.lParam = lpMsg->lParam;
675 DPRINT( "CHAR='%c' %04x %08x\n", wp[0], wp[0], lpMsg->lParam );
676 MsqPostMessage(PsGetWin32Thread()->MessageQueue, &NewMsg, FALSE, QS_KEY);
677 Result = TRUE;
678 }
679 else if (UState == -1)
680 {
681 NewMsg.message =
682 (lpMsg->message == WM_KEYDOWN) ? WM_DEADCHAR : WM_SYSDEADCHAR;
683 NewMsg.hwnd = lpMsg->hwnd;
684 NewMsg.wParam = wp[0];
685 NewMsg.lParam = lpMsg->lParam;
686 dead_char = wp[0];
687 MsqPostMessage(PsGetWin32Thread()->MessageQueue, &NewMsg, FALSE, QS_KEY);
688 Result = TRUE;
689 }
690
691 IntUnLockQueueState;
692 return Result;
693 }
694
695 DWORD
696 STDCALL
697 NtUserGetKeyboardState(
698 LPBYTE lpKeyState)
699 {
700 BOOL Result = TRUE;
701
702 IntLockQueueState;
703 if (lpKeyState) {
704 if(!NT_SUCCESS(MmCopyToCaller(lpKeyState, QueueKeyStateTable, 256)))
705 Result = FALSE;
706 }
707 IntUnLockQueueState;
708 return Result;
709 }
710
711 DWORD
712 STDCALL
713 NtUserSetKeyboardState(
714 LPBYTE lpKeyState)
715 {
716 BOOL Result = TRUE;
717
718 IntLockQueueState;
719 if (lpKeyState) {
720 if(! NT_SUCCESS(MmCopyFromCaller(QueueKeyStateTable, lpKeyState, 256)))
721 Result = FALSE;
722 }
723 IntUnLockQueueState;
724
725 return Result;
726 }
727
728 static UINT VkToScan( UINT Code, BOOL ExtCode, PKBDTABLES pkKT ) {
729 int i;
730
731 for( i = 0; i < pkKT->bMaxVSCtoVK; i++ ) {
732 if( pkKT->pusVSCtoVK[i] == Code ) { return i; }
733 }
734
735 return 0;
736 }
737
738 UINT ScanToVk( UINT Code, BOOL ExtKey, PKBDTABLES pkKT ) {
739 if( !pkKT ) {
740 DPRINT("ScanToVk: No layout\n");
741 return 0;
742 }
743
744 if( ExtKey ) {
745 int i;
746
747 for( i = 0; pkKT->pVSCtoVK_E0[i].Vsc; i++ ) {
748 if( pkKT->pVSCtoVK_E0[i].Vsc == Code )
749 return pkKT->pVSCtoVK_E0[i].Vk & 0xff;
750 }
751 for( i = 0; pkKT->pVSCtoVK_E1[i].Vsc; i++ ) {
752 if( pkKT->pVSCtoVK_E1[i].Vsc == Code )
753 return pkKT->pVSCtoVK_E1[i].Vk & 0xff;
754 }
755
756 return 0;
757 } else {
758 if( Code >= pkKT->bMaxVSCtoVK ) { return 0; }
759 return pkKT->pusVSCtoVK[Code] & 0xff;
760 }
761 }
762
763 /*
764 * Map a virtual key code, or virtual scan code, to a scan code, key code,
765 * or unshifted unicode character.
766 *
767 * Code: See Below
768 * Type:
769 * 0 -- Code is a virtual key code that is converted into a virtual scan code
770 * that does not distinguish between left and right shift keys.
771 * 1 -- Code is a virtual scan code that is converted into a virtual key code
772 * that does not distinguish between left and right shift keys.
773 * 2 -- Code is a virtual key code that is converted into an unshifted unicode
774 * character.
775 * 3 -- Code is a virtual scan code that is converted into a virtual key code
776 * that distinguishes left and right shift keys.
777 * KeyLayout: Keyboard layout handle (currently, unused)
778 *
779 * @implemented
780 */
781
782 static UINT IntMapVirtualKeyEx( UINT Code, UINT Type, PKBDTABLES keyLayout ) {
783 UINT ret = 0;
784
785 switch( Type ) {
786 case 0:
787 if( Code == VK_RSHIFT ) Code = VK_LSHIFT;
788 if( Code == VK_RMENU ) Code = VK_LMENU;
789 if( Code == VK_RCONTROL ) Code = VK_LCONTROL;
790 ret = VkToScan( Code, FALSE, keyLayout );
791 break;
792
793 case 1:
794 ret =
795 DontDistinguishShifts
796 (IntMapVirtualKeyEx( Code, 3, keyLayout ) );
797 break;
798
799 case 2: {
800 WCHAR wp[2];
801
802 ret = VkToScan( Code, FALSE, keyLayout );
803 ToUnicodeInner( Code, ret, 0, wp, 2, 0, keyLayout );
804 ret = wp[0];
805 } break;
806
807 case 3:
808
809 ret = ScanToVk( Code, FALSE, keyLayout );
810 break;
811 }
812
813 return ret;
814 }
815
816 UINT
817 STDCALL
818 NtUserMapVirtualKeyEx( UINT Code, UINT Type, DWORD keyboardId, HKL dwhkl ) {
819 PKBDTABLES keyLayout = PsGetWin32Thread() ?
820 PsGetWin32Thread()->KeyboardLayout : 0;
821
822 if( !keyLayout ) return 0;
823
824 return IntMapVirtualKeyEx( Code, Type, keyLayout );
825 }
826
827
828 int
829 STDCALL
830 NtUserToUnicodeEx(
831 UINT wVirtKey,
832 UINT wScanCode,
833 PBYTE lpKeyState,
834 LPWSTR pwszBuff,
835 int cchBuff,
836 UINT wFlags,
837 HKL dwhkl ) {
838 BYTE KeyStateBuf[0x100];
839 PWCHAR OutPwszBuff = 0;
840 int ret = 0;
841
842
843 if( !NT_SUCCESS(MmCopyFromCaller(KeyStateBuf,
844 lpKeyState,
845 sizeof(KeyStateBuf))) ) {
846 DPRINT1( "Couldn't copy key state from caller.\n" );
847 return 0;
848 }
849 OutPwszBuff = ExAllocatePoolWithTag(NonPagedPool,sizeof(WCHAR) * cchBuff, TAG_STRING);
850 if( !OutPwszBuff ) {
851 DPRINT1( "ExAllocatePool(%d) failed\n", sizeof(WCHAR) * cchBuff);
852 return 0;
853 }
854 RtlZeroMemory( OutPwszBuff, sizeof( WCHAR ) * cchBuff );
855
856 ret = ToUnicodeEx( wVirtKey,
857 wScanCode,
858 KeyStateBuf,
859 OutPwszBuff,
860 cchBuff,
861 wFlags,
862 dwhkl );
863
864 MmCopyToCaller(pwszBuff,OutPwszBuff,sizeof(WCHAR)*cchBuff);
865 ExFreePool(OutPwszBuff);
866
867 return ret;
868 }
869
870 static int W32kSimpleToupper( int ch ) {
871 if( ch >= 'a' && ch <= 'z' ) ch = ch - 'a' + 'A';
872 return ch;
873 }
874
875 DWORD
876 STDCALL
877 NtUserGetKeyNameText( LONG lParam, LPWSTR lpString, int nSize ) {
878 int i;
879 DWORD ret = 0;
880 UINT CareVk = 0;
881 UINT VkCode = 0;
882 UINT ScanCode = (lParam >> 16) & 0xff;
883 BOOL ExtKey = lParam & (1<<24) ? TRUE : FALSE;
884 PKBDTABLES keyLayout =
885 PsGetWin32Thread() ?
886 PsGetWin32Thread()->KeyboardLayout : 0;
887
888 if( !keyLayout || nSize < 1 ) return 0;
889
890 if( lParam & (1<<25) ) {
891 CareVk = VkCode = ScanToVk( ScanCode, ExtKey, keyLayout );
892 if( VkCode == VK_LSHIFT || VkCode == VK_RSHIFT )
893 VkCode = VK_LSHIFT;
894 if( VkCode == VK_LCONTROL || VkCode == VK_RCONTROL )
895 VkCode = VK_LCONTROL;
896 if( VkCode == VK_LMENU || VkCode == VK_RMENU )
897 VkCode = VK_LMENU;
898 } else {
899 VkCode = ScanToVk( ScanCode, ExtKey, keyLayout );
900 }
901
902 VSC_LPWSTR *KeyNames = 0;
903
904 if( CareVk != VkCode )
905 ScanCode = VkToScan( VkCode, ExtKey, keyLayout );
906
907 if( ExtKey )
908 KeyNames = keyLayout->pKeyNamesExt;
909 else
910 KeyNames = keyLayout->pKeyNames;
911
912 for( i = 0; KeyNames[i].pwsz; i++ ) {
913 if( KeyNames[i].vsc == ScanCode ) {
914 UINT StrLen = wcslen(KeyNames[i].pwsz);
915 UINT StrMax = StrLen > (nSize - 1) ? (nSize - 1) : StrLen;
916 WCHAR null_wc = 0;
917 if( NT_SUCCESS( MmCopyToCaller( lpString,
918 KeyNames[i].pwsz,
919 StrMax * sizeof(WCHAR) ) ) &&
920 NT_SUCCESS( MmCopyToCaller( lpString + StrMax,
921 &null_wc,
922 sizeof( WCHAR ) ) ) ) {
923 ret = StrMax;
924 break;
925 }
926 }
927 }
928
929 if( ret == 0 ) {
930 WCHAR UCName[2];
931
932 UCName[0] = W32kSimpleToupper(IntMapVirtualKeyEx( VkCode, 2, keyLayout ));
933 UCName[1] = 0;
934 ret = 1;
935
936 if( !NT_SUCCESS(MmCopyToCaller( lpString, UCName, 2 * sizeof(WCHAR) )) )
937 return 0;
938 }
939
940 return ret;
941 }
942
943 /*
944 * Filter this message according to the current key layout, setting wParam
945 * appropriately.
946 */
947
948 VOID FASTCALL W32kKeyProcessMessage(LPMSG Msg, PKBDTABLES KeyboardLayout) {
949 DWORD ScanCode = 0, ModifierBits = 0;
950 DWORD i = 0;
951 DWORD BaseMapping = 0;
952 DWORD RawVk = 0;
953 static WORD NumpadConversion[][2] =
954 { { VK_DELETE, VK_DECIMAL },
955 { VK_INSERT, VK_NUMPAD0 },
956 { VK_END, VK_NUMPAD1 },
957 { VK_DOWN, VK_NUMPAD2 },
958 { VK_NEXT, VK_NUMPAD3 },
959 { VK_LEFT, VK_NUMPAD4 },
960 { VK_CLEAR, VK_NUMPAD5 },
961 { VK_RIGHT, VK_NUMPAD6 },
962 { VK_HOME, VK_NUMPAD7 },
963 { VK_UP, VK_NUMPAD8 },
964 { VK_PRIOR, VK_NUMPAD9 },
965 { 0,0 } };
966
967 if( !KeyboardLayout || !Msg ||
968 (Msg->message != WM_KEYDOWN && Msg->message != WM_SYSKEYDOWN &&
969 Msg->message != WM_KEYUP && Msg->message != WM_SYSKEYUP) )
970 {
971 return;
972 }
973
974 IntLockQueueState;
975
976 /* arty -- handle numpad -- On real windows, the actual key produced
977 * by the messaging layer is different based on the state of numlock. */
978 ModifierBits = ModBits(KeyboardLayout,QueueKeyStateTable);
979
980 /* Get the raw scan code, so we can look up whether the key is a numpad
981 * key
982 *
983 * Shift and the LP_EXT_BIT cancel. */
984 ScanCode = (Msg->lParam >> 16) & 0xff;
985 BaseMapping = Msg->wParam =
986 IntMapVirtualKeyEx( ScanCode, 1, KeyboardLayout );
987 if( ScanCode >= KeyboardLayout->bMaxVSCtoVK )
988 RawVk = 0;
989 else
990 RawVk = KeyboardLayout->pusVSCtoVK[ScanCode];
991
992 if ((ModifierBits & NUMLOCK_BIT) &&
993 !(ModifierBits & GetShiftBit(KeyboardLayout, VK_SHIFT)) &&
994 (RawVk & KNUMP) &&
995 !(Msg->lParam & LP_EXT_BIT))
996 {
997 /* The key in question is a numpad key. Search for a translation. */
998 for (i = 0; NumpadConversion[i][0]; i++)
999 {
1000 if ((BaseMapping & 0xff) == NumpadConversion[i][0]) /* RawVk? */
1001 {
1002 Msg->wParam = NumpadConversion[i][1];
1003 break;
1004 }
1005 }
1006 }
1007
1008 DPRINT("Key: [%04x -> %04x]\n", BaseMapping, Msg->wParam);
1009
1010 /* Now that we have the VK, we can set the keymap appropriately
1011 * This is a better place for this code, as it's guaranteed to be
1012 * run, unlike translate message. */
1013 if (Msg->message == WM_KEYDOWN || Msg->message == WM_SYSKEYDOWN)
1014 {
1015 SetKeyState( ScanCode, Msg->wParam, Msg->lParam & LP_EXT_BIT,
1016 TRUE ); /* Strike key */
1017 }
1018 else if (Msg->message == WM_KEYUP || Msg->message == WM_SYSKEYUP)
1019 {
1020 SetKeyState( ScanCode, Msg->wParam, Msg->lParam & LP_EXT_BIT,
1021 FALSE ); /* Release key */
1022 }
1023
1024 /* We need to unset SYSKEYDOWN if the ALT key is an ALT+Gr */
1025 if( QueueKeyStateTable[VK_RMENU] & KS_DOWN_BIT ) {
1026 if( Msg->message == WM_SYSKEYDOWN ) Msg->message = WM_KEYDOWN;
1027 else Msg->message = WM_KEYUP;
1028 }
1029
1030 IntUnLockQueueState;
1031 }
1032 /* EOF */