Update the queue key state even if no window has the focus (spotted by
[wine] / windows / input.c
1 /*
2  * USER Input processing
3  *
4  * Copyright 1993 Bob Amstadt
5  * Copyright 1996 Albrecht Kleine 
6  * Copyright 1997 David Faure
7  * Copyright 1998 Morten Welinder
8  * Copyright 1998 Ulrich Weigand
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <ctype.h>
29 #include <assert.h>
30
31 #include "windef.h"
32 #include "winnls.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winuser.h"
36 #include "wine/winbase16.h"
37 #include "wine/winuser16.h"
38 #include "wine/server.h"
39 #include "win.h"
40 #include "hook.h"
41 #include "input.h"
42 #include "message.h"
43 #include "queue.h"
44 #include "wine/debug.h"
45 #include "winerror.h"
46
47 WINE_DECLARE_DEBUG_CHANNEL(key);
48 WINE_DECLARE_DEBUG_CHANNEL(keyboard);
49 WINE_DECLARE_DEBUG_CHANNEL(win);
50 WINE_DEFAULT_DEBUG_CHANNEL(event);
51
52 static BOOL InputEnabled = TRUE;
53 static BOOL SwappedButtons;
54
55 BYTE InputKeyStateTable[256];
56 BYTE AsyncKeyStateTable[256];
57
58 /* Storage for the USER-maintained mouse positions */
59 static DWORD PosX, PosY;
60
61 typedef union
62 {
63     struct
64     {
65         unsigned long count : 16;
66         unsigned long code : 8;
67         unsigned long extended : 1;
68         unsigned long unused : 2;
69         unsigned long win_internal : 2;
70         unsigned long context : 1;
71         unsigned long previous : 1;
72         unsigned long transition : 1;
73     } lp1;
74     unsigned long lp2;
75 } KEYLP;
76
77
78 /***********************************************************************
79  *           get_key_state
80  */
81 static WORD get_key_state(void)
82 {
83     WORD ret = 0;
84
85     if (SwappedButtons)
86     {
87         if (InputKeyStateTable[VK_RBUTTON] & 0x80) ret |= MK_LBUTTON;
88         if (InputKeyStateTable[VK_LBUTTON] & 0x80) ret |= MK_RBUTTON;
89     }
90     else
91     {
92         if (InputKeyStateTable[VK_LBUTTON] & 0x80) ret |= MK_LBUTTON;
93         if (InputKeyStateTable[VK_RBUTTON] & 0x80) ret |= MK_RBUTTON;
94     }
95     if (InputKeyStateTable[VK_MBUTTON] & 0x80)  ret |= MK_MBUTTON;
96     if (InputKeyStateTable[VK_SHIFT] & 0x80)    ret |= MK_SHIFT;
97     if (InputKeyStateTable[VK_CONTROL] & 0x80)  ret |= MK_CONTROL;
98     if (InputKeyStateTable[VK_XBUTTON1] & 0x80) ret |= MK_XBUTTON1;
99     if (InputKeyStateTable[VK_XBUTTON2] & 0x80) ret |= MK_XBUTTON2;
100     return ret;
101 }
102
103
104 /***********************************************************************
105  *           queue_raw_hardware_message
106  *
107  * Add a message to the raw hardware queue.
108  * Note: the position is relative to the desktop window.
109  */
110 static void queue_raw_hardware_message( UINT message, WPARAM wParam, LPARAM lParam,
111                                         int xPos, int yPos, DWORD time, ULONG_PTR extraInfo )
112 {
113     SERVER_START_REQ( send_message )
114     {
115         req->id     = (void *)GetCurrentThreadId();
116         req->type   = MSG_HARDWARE_RAW;
117         req->win    = 0;
118         req->msg    = message;
119         req->wparam = wParam;
120         req->lparam = lParam;
121         req->x      = xPos;
122         req->y      = yPos;
123         req->time   = time;
124         req->info   = extraInfo;
125         req->timeout = 0;
126         wine_server_call( req );
127     }
128     SERVER_END_REQ;
129 }
130
131
132 /***********************************************************************
133  *           queue_kbd_event
134  *
135  * Put a keyboard event into a thread queue
136  */
137 static void queue_kbd_event( const KEYBDINPUT *ki, UINT injected_flags )
138 {
139     UINT message;
140     KEYLP keylp;
141     KBDLLHOOKSTRUCT hook;
142
143     keylp.lp2 = 0;
144     keylp.lp1.count = 1;
145     keylp.lp1.code = ki->wScan;
146     keylp.lp1.extended = (ki->dwFlags & KEYEVENTF_EXTENDEDKEY) != 0;
147     keylp.lp1.win_internal = 0; /* this has something to do with dialogs,
148                                 * don't remember where I read it - AK */
149                                 /* it's '1' under windows, when a dialog box appears
150                                  * and you press one of the underlined keys - DF*/
151
152     if (ki->dwFlags & KEYEVENTF_KEYUP )
153     {
154         BOOL sysKey = (InputKeyStateTable[VK_MENU] & 0x80) &&
155                       !(InputKeyStateTable[VK_CONTROL] & 0x80);
156         InputKeyStateTable[ki->wVk] &= ~0x80;
157         keylp.lp1.previous = 1;
158         keylp.lp1.transition = 1;
159         message = sysKey ? WM_SYSKEYUP : WM_KEYUP;
160     }
161     else
162     {
163         keylp.lp1.previous = (InputKeyStateTable[ki->wVk] & 0x80) != 0;
164         keylp.lp1.transition = 0;
165         if (!(InputKeyStateTable[ki->wVk] & 0x80)) InputKeyStateTable[ki->wVk] ^= 0x01;
166         InputKeyStateTable[ki->wVk] |= 0x80;
167         AsyncKeyStateTable[ki->wVk] |= 0x80;
168
169         message = (InputKeyStateTable[VK_MENU] & 0x80) && !(InputKeyStateTable[VK_CONTROL] & 0x80)
170               ? WM_SYSKEYDOWN : WM_KEYDOWN;
171     }
172
173     if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP )
174         keylp.lp1.context = (InputKeyStateTable[VK_MENU] & 0x80) != 0; /* 1 if alt */
175
176     TRACE_(key)(" wParam=%04x, lParam=%08lx, InputKeyState=%x\n",
177                 ki->wVk, keylp.lp2, InputKeyStateTable[ki->wVk] );
178
179     hook.vkCode      = ki->wVk;
180     hook.scanCode    = ki->wScan;
181     hook.flags       = (keylp.lp2 >> 24) | injected_flags;
182     hook.time        = ki->time;
183     hook.dwExtraInfo = ki->dwExtraInfo;
184     if (!HOOK_CallHooksW( WH_KEYBOARD_LL, HC_ACTION, message, (LPARAM)&hook ))
185         queue_raw_hardware_message( message, ki->wVk, keylp.lp2,
186                                     PosX, PosY, ki->time, ki->dwExtraInfo );
187 }
188
189
190 /***********************************************************************
191  *           queue_raw_mouse_message
192  */
193 static void queue_raw_mouse_message( UINT message, UINT flags, INT x, INT y, const MOUSEINPUT *mi )
194 {
195     MSLLHOOKSTRUCT hook;
196
197     hook.pt.x        = x;
198     hook.pt.y        = y;
199     hook.mouseData   = MAKELONG( 0, mi->mouseData );
200     hook.flags       = flags;
201     hook.time        = mi->time;
202     hook.dwExtraInfo = mi->dwExtraInfo;
203
204     if (!HOOK_CallHooksW( WH_MOUSE_LL, HC_ACTION, message, (LPARAM)&hook ))
205         queue_raw_hardware_message( message, MAKEWPARAM( get_key_state(), mi->mouseData ),
206                                     0, x, y, mi->time, mi->dwExtraInfo );
207 }
208
209
210 /***********************************************************************
211  *              queue_mouse_event
212  */
213 static void queue_mouse_event( const MOUSEINPUT *mi, UINT flags )
214 {
215     if (mi->dwFlags & MOUSEEVENTF_ABSOLUTE)
216     {
217         PosX = (mi->dx * GetSystemMetrics(SM_CXSCREEN)) >> 16;
218         PosY = (mi->dy * GetSystemMetrics(SM_CYSCREEN)) >> 16;
219     }
220     else if (mi->dwFlags & MOUSEEVENTF_MOVE)
221     {
222         int width  = GetSystemMetrics(SM_CXSCREEN);
223         int height = GetSystemMetrics(SM_CYSCREEN);
224         long posX = (long) PosX, posY = (long) PosY;
225         int accel[3];
226         int accelMult;
227
228         /* dx and dy can be negative numbers for relative movements */
229         SystemParametersInfoA(SPI_GETMOUSE, 0, accel, 0);
230
231         accelMult = 1;
232         if (mi->dx > accel[0] && accel[2] != 0)
233         {
234             accelMult = 2;
235             if ((mi->dx > accel[1]) && (accel[2] == 2))
236             {
237                 accelMult = 4;
238             }
239         }
240         posX += (long)mi->dx * accelMult;
241
242         accelMult = 1;
243         if (mi->dy > accel[0] && accel[2] != 0)
244         {
245             accelMult = 2;
246             if ((mi->dy > accel[1]) && (accel[2] == 2))
247             {
248                 accelMult = 4;
249             }
250         }
251         posY += (long)mi->dy * accelMult;
252
253         /* Clip to the current screen size */
254         if (posX < 0) PosX = 0;
255         else if (posX >= width) PosX = width - 1;
256         else PosX = posX;
257
258         if (posY < 0) PosY = 0;
259         else if (posY >= height) PosY = height - 1;
260         else PosY = posY;
261     }
262
263     if (mi->dwFlags & MOUSEEVENTF_MOVE)
264     {
265         queue_raw_mouse_message( WM_MOUSEMOVE, flags, PosX, PosY, mi );
266     }
267     if (mi->dwFlags & MOUSEEVENTF_LEFTDOWN)
268     {
269         InputKeyStateTable[VK_LBUTTON] |= 0x80;
270         AsyncKeyStateTable[VK_LBUTTON] |= 0x80;
271         queue_raw_mouse_message( SwappedButtons ? WM_RBUTTONDOWN : WM_LBUTTONDOWN,
272                                  flags, PosX, PosY, mi );
273     }
274     if (mi->dwFlags & MOUSEEVENTF_LEFTUP)
275     {
276         InputKeyStateTable[VK_LBUTTON] &= ~0x80;
277         queue_raw_mouse_message( SwappedButtons ? WM_RBUTTONUP : WM_LBUTTONUP,
278                                  flags, PosX, PosY, mi );
279     }
280     if (mi->dwFlags & MOUSEEVENTF_RIGHTDOWN)
281     {
282         InputKeyStateTable[VK_RBUTTON] |= 0x80;
283         AsyncKeyStateTable[VK_RBUTTON] |= 0x80;
284         queue_raw_mouse_message( SwappedButtons ? WM_LBUTTONDOWN : WM_RBUTTONDOWN,
285                                  flags, PosX, PosY, mi );
286     }
287     if (mi->dwFlags & MOUSEEVENTF_RIGHTUP)
288     {
289         InputKeyStateTable[VK_RBUTTON] &= ~0x80;
290         queue_raw_mouse_message( SwappedButtons ? WM_LBUTTONUP : WM_RBUTTONUP,
291                                  flags, PosX, PosY, mi );
292     }
293     if (mi->dwFlags & MOUSEEVENTF_MIDDLEDOWN)
294     {
295         InputKeyStateTable[VK_MBUTTON] |= 0x80;
296         AsyncKeyStateTable[VK_MBUTTON] |= 0x80;
297         queue_raw_mouse_message( WM_MBUTTONDOWN, flags, PosX, PosY, mi );
298     }
299     if (mi->dwFlags & MOUSEEVENTF_MIDDLEUP)
300     {
301         InputKeyStateTable[VK_MBUTTON] &= ~0x80;
302         queue_raw_mouse_message( WM_MBUTTONUP, flags, PosX, PosY, mi );
303     }
304     if (mi->dwFlags & MOUSEEVENTF_WHEEL)
305     {
306         queue_raw_mouse_message( WM_MOUSEWHEEL, flags, PosX, PosY, mi );
307     }
308     if (flags & LLMHF_INJECTED)  /* we have to actually move the cursor */
309         SetCursorPos( PosX, PosY );
310 }
311
312
313 /***********************************************************************
314  *              SendInput  (USER32.@)
315  */
316 UINT WINAPI SendInput( UINT count, LPINPUT inputs, int size )
317 {
318     UINT i;
319
320     if (!InputEnabled) return 0;
321
322     for (i = 0; i < count; i++, inputs++)
323     {
324         switch(inputs->type)
325         {
326         case INPUT_MOUSE:
327             queue_mouse_event( &inputs->u.mi, LLMHF_INJECTED );
328             break;
329         case WINE_INTERNAL_INPUT_MOUSE:
330             queue_mouse_event( &inputs->u.mi, 0 );
331             break;
332         case INPUT_KEYBOARD:
333             queue_kbd_event( &inputs->u.ki, LLKHF_INJECTED );
334             break;
335         case WINE_INTERNAL_INPUT_KEYBOARD:
336             queue_kbd_event( &inputs->u.ki, 0 );
337             break;
338         case INPUT_HARDWARE:
339             FIXME( "INPUT_HARDWARE not supported\n" );
340             break;
341         }
342     }
343     return count;
344 }
345
346
347 /***********************************************************************
348  *              keybd_event (USER32.@)
349  */
350 void WINAPI keybd_event( BYTE bVk, BYTE bScan,
351                          DWORD dwFlags, DWORD dwExtraInfo )
352 {
353     INPUT input;
354
355     input.type = INPUT_KEYBOARD;
356     input.u.ki.wVk = bVk;
357     input.u.ki.wScan = bScan;
358     input.u.ki.dwFlags = dwFlags;
359     input.u.ki.time = GetTickCount();
360     input.u.ki.dwExtraInfo = dwExtraInfo;
361     SendInput( 1, &input, sizeof(input) );
362 }
363
364
365 /***********************************************************************
366  *              keybd_event (USER.289)
367  */
368 void WINAPI keybd_event16( CONTEXT86 *context )
369 {
370     DWORD dwFlags = 0;
371
372     if (AH_reg(context) & 0x80) dwFlags |= KEYEVENTF_KEYUP;
373     if (BH_reg(context) & 1   ) dwFlags |= KEYEVENTF_EXTENDEDKEY;
374
375     keybd_event( AL_reg(context), BL_reg(context),
376                  dwFlags, MAKELONG(SI_reg(context), DI_reg(context)) );
377 }
378
379
380 /***********************************************************************
381  *              mouse_event (USER32.@)
382  */
383 void WINAPI mouse_event( DWORD dwFlags, DWORD dx, DWORD dy,
384                          DWORD dwData, DWORD dwExtraInfo )
385 {
386     INPUT input;
387
388     input.type = INPUT_MOUSE;
389     input.u.mi.dx = dx;
390     input.u.mi.dy = dy;
391     input.u.mi.mouseData = dwData;
392     input.u.mi.dwFlags = dwFlags;
393     input.u.mi.time = GetCurrentTime();
394     input.u.mi.dwExtraInfo = dwExtraInfo;
395     SendInput( 1, &input, sizeof(input) );
396 }
397
398
399 /***********************************************************************
400  *              mouse_event (USER.299)
401  */
402 void WINAPI mouse_event16( CONTEXT86 *context )
403 {
404     mouse_event( AX_reg(context), BX_reg(context), CX_reg(context),
405                  DX_reg(context), MAKELONG(SI_reg(context), DI_reg(context)) );
406 }
407
408 /***********************************************************************
409  *              GetMouseEventProc (USER.337)
410  */
411 FARPROC16 WINAPI GetMouseEventProc16(void)
412 {
413     HMODULE16 hmodule = GetModuleHandle16("USER");
414     return GetProcAddress16( hmodule, "mouse_event" );
415 }
416
417
418 /**********************************************************************
419  *              EnableHardwareInput (USER.331)
420  */
421 BOOL16 WINAPI EnableHardwareInput16(BOOL16 bEnable)
422 {
423   BOOL16 bOldState = InputEnabled;
424   FIXME_(event)("(%d) - stub\n", bEnable);
425   InputEnabled = bEnable;
426   return bOldState;
427 }
428
429
430 /***********************************************************************
431  *              SwapMouseButton (USER.186)
432  */
433 BOOL16 WINAPI SwapMouseButton16( BOOL16 fSwap )
434 {
435     BOOL16 ret = SwappedButtons;
436     SwappedButtons = fSwap;
437     return ret;
438 }
439
440
441 /***********************************************************************
442  *              SwapMouseButton (USER32.@)
443  */
444 BOOL WINAPI SwapMouseButton( BOOL fSwap )
445 {
446     BOOL ret = SwappedButtons;
447     SwappedButtons = fSwap;
448     return ret;
449 }
450
451
452 /***********************************************************************
453  *              GetCursorPos (USER.17)
454  */
455 BOOL16 WINAPI GetCursorPos16( POINT16 *pt )
456 {
457     POINT pos;
458     if (!pt) return 0;
459     GetCursorPos(&pos);
460     pt->x = pos.x;
461     pt->y = pos.y;
462     return 1;
463 }
464
465
466 /***********************************************************************
467  *              GetCursorPos (USER32.@)
468  */
469 BOOL WINAPI GetCursorPos( POINT *pt )
470 {
471     if (!pt) return 0;
472     pt->x = PosX;
473     pt->y = PosY;
474     if (USER_Driver.pGetCursorPos) USER_Driver.pGetCursorPos( pt );
475     return 1;
476 }
477
478
479 /***********************************************************************
480  *              SetCursorPos (USER.70)
481  */
482 void WINAPI SetCursorPos16( INT16 x, INT16 y )
483 {
484     SetCursorPos( x, y );
485 }
486
487
488 /***********************************************************************
489  *              SetCursorPos (USER32.@)
490  */
491 BOOL WINAPI SetCursorPos( INT x, INT y )
492 {
493     if (USER_Driver.pSetCursorPos) USER_Driver.pSetCursorPos( x, y );
494     PosX = x;
495     PosY = y;
496     return TRUE;
497 }
498
499
500 /**********************************************************************
501  *              EVENT_Capture
502  *
503  * We need this to be able to generate double click messages
504  * when menu code captures mouse in the window without CS_DBLCLK style.
505  */
506 HWND EVENT_Capture(HWND hwnd, INT16 ht)
507 {
508     HWND capturePrev = 0, captureWnd = 0;
509     MESSAGEQUEUE *pMsgQ = 0, *pCurMsgQ = 0;
510     WND* wndPtr = 0;
511     INT16 captureHT = 0;
512
513     capturePrev = GetCapture();
514
515     if (!hwnd)
516     {
517         captureWnd = 0;
518         captureHT = 0;
519     }
520     else
521     {
522         wndPtr = WIN_FindWndPtr( hwnd );
523         if (wndPtr)
524         {
525             TRACE_(win)("(0x%04x)\n", hwnd );
526             captureWnd   = wndPtr->hwndSelf;
527             captureHT    = ht;
528         }
529     }
530
531     /* Get the messageQ for the current thread */
532     if (!(pCurMsgQ = QUEUE_Current()))
533     {
534         WARN_(win)("\tCurrent message queue not found. Exiting!\n" );
535         goto CLEANUP;
536     }
537
538     /* Update the perQ capture window and send messages */
539     if( capturePrev != captureWnd )
540     {
541         if (wndPtr)
542         {
543             /* Retrieve the message queue associated with this window */
544             pMsgQ = (MESSAGEQUEUE *)QUEUE_Lock( wndPtr->hmemTaskQ );
545             if ( !pMsgQ )
546             {
547                 WARN_(win)("\tMessage queue not found. Exiting!\n" );
548                 goto CLEANUP;
549             }
550
551             /* Make sure that message queue for the window we are setting capture to
552              * shares the same perQ data as the current threads message queue.
553              */
554             if ( pCurMsgQ->pQData != pMsgQ->pQData )
555                 goto CLEANUP;
556         }
557
558         PERQDATA_SetCaptureWnd( captureWnd, captureHT );
559         if (capturePrev) SendMessageA( capturePrev, WM_CAPTURECHANGED, 0, (LPARAM)hwnd );
560     }
561
562 CLEANUP:
563     /* Unlock the queues before returning */
564     if ( pMsgQ )
565         QUEUE_Unlock( pMsgQ );
566
567     WIN_ReleaseWndPtr(wndPtr);
568     return capturePrev;
569 }
570
571
572 /**********************************************************************
573  *              SetCapture (USER32.@)
574  */
575 HWND WINAPI SetCapture( HWND hwnd )
576 {
577     return EVENT_Capture( hwnd, HTCLIENT );
578 }
579
580
581 /**********************************************************************
582  *              ReleaseCapture (USER32.@)
583  */
584 BOOL WINAPI ReleaseCapture(void)
585 {
586     return (EVENT_Capture( 0, 0 ) != 0);
587 }
588
589
590 /**********************************************************************
591  *              GetCapture (USER32.@)
592  */
593 HWND WINAPI GetCapture(void)
594 {
595     INT hittest;
596     return PERQDATA_GetCaptureWnd( &hittest );
597 }
598
599 /**********************************************************************
600  *              GetAsyncKeyState (USER32.@)
601  *
602  *      Determine if a key is or was pressed.  retval has high-order 
603  * bit set to 1 if currently pressed, low-order bit set to 1 if key has
604  * been pressed.
605  *
606  *      This uses the variable AsyncMouseButtonsStates and
607  * AsyncKeyStateTable (set in event.c) which have the mouse button
608  * number or key number (whichever is applicable) set to true if the
609  * mouse or key had been depressed since the last call to 
610  * GetAsyncKeyState.
611  */
612 SHORT WINAPI GetAsyncKeyState(INT nKey)
613 {
614     SHORT retval = ((AsyncKeyStateTable[nKey] & 0x80) ? 0x0001 : 0) |
615                    ((InputKeyStateTable[nKey] & 0x80) ? 0x8000 : 0);
616     AsyncKeyStateTable[nKey] = 0;
617     TRACE_(key)("(%x) -> %x\n", nKey, retval);
618     return retval;
619 }
620
621 /**********************************************************************
622  *              GetAsyncKeyState (USER.249)
623  */
624 INT16 WINAPI GetAsyncKeyState16(INT16 nKey)
625 {
626     return GetAsyncKeyState(nKey);
627 }
628
629 /***********************************************************************
630  *              IsUserIdle (USER.333)
631  */
632 BOOL16 WINAPI IsUserIdle16(void)
633 {
634     if ( GetAsyncKeyState( VK_LBUTTON ) & 0x8000 )
635         return FALSE;
636
637     if ( GetAsyncKeyState( VK_RBUTTON ) & 0x8000 )
638         return FALSE;
639
640     if ( GetAsyncKeyState( VK_MBUTTON ) & 0x8000 )
641         return FALSE;
642
643     /* Should check for screen saver activation here ... */
644
645     return TRUE;
646 }
647
648 /**********************************************************************
649  *              VkKeyScanA (USER32.@)
650  *
651  * VkKeyScan translates an ANSI character to a virtual-key and shift code
652  * for the current keyboard.
653  * high-order byte yields :
654  *      0       Unshifted
655  *      1       Shift
656  *      2       Ctrl
657  *      3-5     Shift-key combinations that are not used for characters
658  *      6       Ctrl-Alt
659  *      7       Ctrl-Alt-Shift
660  *      I.e. :  Shift = 1, Ctrl = 2, Alt = 4.
661  * FIXME : works ok except for dead chars :
662  * VkKeyScan '^'(0x5e, 94) ... got keycode 00 ... returning 00
663  * VkKeyScan '`'(0x60, 96) ... got keycode 00 ... returning 00
664  */
665 WORD WINAPI VkKeyScanA(CHAR cChar)
666 {
667     return USER_Driver.pVkKeyScan( cChar );
668 }
669
670 /******************************************************************************
671  *              VkKeyScanW (USER32.@)
672  */
673 WORD WINAPI VkKeyScanW(WCHAR cChar)
674 {
675         return VkKeyScanA((CHAR)cChar); /* FIXME: check unicode */
676 }
677
678 /**********************************************************************
679  *              VkKeyScanExA (USER32.@)
680  */
681 WORD WINAPI VkKeyScanExA(CHAR cChar, HKL dwhkl)
682 {
683     /* FIXME: complete workaround this is */
684     return VkKeyScanA(cChar);
685 }
686
687 /******************************************************************************
688  *              VkKeyScanExW (USER32.@)
689  */
690 WORD WINAPI VkKeyScanExW(WCHAR cChar, HKL dwhkl)
691 {
692     /* FIXME: complete workaround this is */
693     return VkKeyScanA((CHAR)cChar); /* FIXME: check unicode */
694 }
695
696 /******************************************************************************
697  *              GetKeyboardType (USER32.@)
698  */
699 INT WINAPI GetKeyboardType(INT nTypeFlag)
700 {
701     TRACE_(keyboard)("(%d)\n", nTypeFlag);
702     switch(nTypeFlag)
703     {
704     case 0:      /* Keyboard type */
705         return 4;    /* AT-101 */
706     case 1:      /* Keyboard Subtype */
707         return 0;    /* There are no defined subtypes */
708     case 2:      /* Number of F-keys */
709         return 12;   /* We're doing an 101 for now, so return 12 F-keys */
710     default:
711         WARN_(keyboard)("Unknown type\n");
712         return 0;    /* The book says 0 here, so 0 */
713     }
714 }
715
716 /******************************************************************************
717  *              MapVirtualKeyA (USER32.@)
718  */
719 UINT WINAPI MapVirtualKeyA(UINT code, UINT maptype)
720 {
721     return USER_Driver.pMapVirtualKey( code, maptype );
722 }
723
724 /******************************************************************************
725  *              MapVirtualKeyW (USER32.@)
726  */
727 UINT WINAPI MapVirtualKeyW(UINT code, UINT maptype)
728 {
729     return MapVirtualKeyA(code,maptype);
730 }
731
732 /******************************************************************************
733  *              MapVirtualKeyExA (USER32.@)
734  */
735 UINT WINAPI MapVirtualKeyExA(UINT code, UINT maptype, HKL hkl)
736 {
737     if (hkl)
738         FIXME_(keyboard)("(%d,%d,0x%08lx), hkl unhandled!\n",code,maptype,(DWORD)hkl);
739     return MapVirtualKeyA(code,maptype);
740 }
741
742 /******************************************************************************
743  *              MapVirtualKeyExW (USER32.@)
744  */
745 UINT WINAPI MapVirtualKeyExW(UINT code, UINT maptype, HKL hkl)
746 {
747     if (hkl)
748         FIXME_(keyboard)("(%d,%d,0x%08lx), hkl unhandled!\n",code,maptype,(DWORD)hkl);
749     return MapVirtualKeyA(code,maptype);
750 }
751
752 /****************************************************************************
753  *              GetKBCodePage (USER32.@)
754  */
755 UINT WINAPI GetKBCodePage(void)
756 {
757     return GetOEMCP();
758 }
759
760 /****************************************************************************
761  *              GetKeyboardLayoutName (USER.477)
762  */
763 INT16 WINAPI GetKeyboardLayoutName16(LPSTR pwszKLID)
764 {
765         return GetKeyboardLayoutNameA(pwszKLID);
766 }
767
768 /***********************************************************************
769  *              GetKeyboardLayout (USER32.@)
770  *
771  * FIXME: - device handle for keyboard layout defaulted to 
772  *          the language id. This is the way Windows default works.
773  *        - the thread identifier (dwLayout) is also ignored.
774  */
775 HKL WINAPI GetKeyboardLayout(DWORD dwLayout)
776 {
777         HKL layout;
778         layout = GetSystemDefaultLCID(); /* FIXME */
779         layout |= (layout<<16);          /* FIXME */
780         TRACE_(keyboard)("returning %08x\n",layout);
781         return layout;
782 }
783
784 /****************************************************************************
785  *              GetKeyboardLayoutNameA (USER32.@)
786  */
787 INT WINAPI GetKeyboardLayoutNameA(LPSTR pwszKLID)
788 {
789         sprintf(pwszKLID, "%08x",GetKeyboardLayout(0));
790         return 1;
791 }
792
793 /****************************************************************************
794  *              GetKeyboardLayoutNameW (USER32.@)
795  */
796 INT WINAPI GetKeyboardLayoutNameW(LPWSTR pwszKLID)
797 {
798         char buf[KL_NAMELENGTH];
799         int res = GetKeyboardLayoutNameA(buf);
800         MultiByteToWideChar( CP_ACP, 0, buf, -1, pwszKLID, KL_NAMELENGTH );
801         return res;
802 }
803
804 /****************************************************************************
805  *              GetKeyNameTextA (USER32.@)
806  */
807 INT WINAPI GetKeyNameTextA(LONG lParam, LPSTR lpBuffer, INT nSize)
808 {
809     return USER_Driver.pGetKeyNameText( lParam, lpBuffer, nSize );
810 }
811
812 /****************************************************************************
813  *              GetKeyNameTextW (USER32.@)
814  */
815 INT WINAPI GetKeyNameTextW(LONG lParam, LPWSTR lpBuffer, INT nSize)
816 {
817         int res;
818         LPSTR buf = HeapAlloc( GetProcessHeap(), 0, nSize );
819         if(buf == NULL) return 0; /* FIXME: is this the correct failure value?*/
820         res = GetKeyNameTextA(lParam,buf,nSize);
821
822         if (nSize > 0 && !MultiByteToWideChar( CP_ACP, 0, buf, -1, lpBuffer, nSize ))
823             lpBuffer[nSize-1] = 0;
824         HeapFree( GetProcessHeap(), 0, buf );
825         return res;
826 }
827
828 /****************************************************************************
829  *              ToUnicode (USER32.@)
830  */
831 INT WINAPI ToUnicode(UINT virtKey, UINT scanCode, LPBYTE lpKeyState,
832                      LPWSTR lpwStr, int size, UINT flags)
833 {
834     return USER_Driver.pToUnicode(virtKey, scanCode, lpKeyState, lpwStr, size, flags);
835 }
836
837 /****************************************************************************
838  *              ToUnicodeEx (USER32.@)
839  */
840 INT WINAPI ToUnicodeEx(UINT virtKey, UINT scanCode, LPBYTE lpKeyState,
841                        LPWSTR lpwStr, int size, UINT flags, HKL hkl)
842 {
843     /* FIXME: need true implementation */
844     return ToUnicode(virtKey, scanCode, lpKeyState, lpwStr, size, flags);
845 }
846
847 /****************************************************************************
848  *              ToAscii (USER32.@)
849  */
850 INT WINAPI ToAscii( UINT virtKey,UINT scanCode,LPBYTE lpKeyState,
851                         LPWORD lpChar,UINT flags )
852 {
853     WCHAR uni_chars[2];
854     INT ret, n_ret;
855
856     ret = ToUnicode(virtKey, scanCode, lpKeyState, uni_chars, 2, flags);
857     if(ret < 0) n_ret = 1; /* FIXME: make ToUnicode return 2 for dead chars */
858     else n_ret = ret;
859     WideCharToMultiByte(CP_ACP, 0, uni_chars, n_ret, (LPSTR)lpChar, 2, NULL, NULL);
860     return ret;
861 }
862
863 /****************************************************************************
864  *              ToAsciiEx (USER32.@)
865  */
866 INT WINAPI ToAsciiEx( UINT virtKey, UINT scanCode, LPBYTE lpKeyState,
867                       LPWORD lpChar, UINT flags, HKL dwhkl )
868 {
869     /* FIXME: need true implementation */
870     return ToAscii(virtKey, scanCode, lpKeyState, lpChar, flags);
871 }
872
873 /**********************************************************************
874  *              ActivateKeyboardLayout (USER32.@)
875  *
876  * Call ignored. WINE supports only system default keyboard layout.
877  */
878 HKL WINAPI ActivateKeyboardLayout(HKL hLayout, UINT flags)
879 {
880     TRACE_(keyboard)("(%d, %d)\n", hLayout, flags);
881     ERR_(keyboard)("Only default system keyboard layout supported. Call ignored.\n");
882     return 0;
883 }
884
885
886 /***********************************************************************
887  *              GetKeyboardLayoutList (USER32.@)
888  *
889  * FIXME: Supports only the system default language and layout and 
890  *          returns only 1 value.
891  *
892  * Return number of values available if either input parm is 
893  *  0, per MS documentation.
894  *
895  */
896 INT WINAPI GetKeyboardLayoutList(INT nBuff,HKL *layouts)
897 {
898         TRACE_(keyboard)("(%d,%p)\n",nBuff,layouts);
899         if (!nBuff || !layouts)
900             return 1;
901         if (layouts)
902                 layouts[0] = GetKeyboardLayout(0);
903         return 1;
904 }
905
906
907 /***********************************************************************
908  *              RegisterHotKey (USER32.@)
909  */
910 BOOL WINAPI RegisterHotKey(HWND hwnd,INT id,UINT modifiers,UINT vk) {
911         FIXME_(keyboard)("(0x%08x,%d,0x%08x,%d): stub\n",hwnd,id,modifiers,vk);
912         return TRUE;
913 }
914
915 /***********************************************************************
916  *              UnregisterHotKey (USER32.@)
917  */
918 BOOL WINAPI UnregisterHotKey(HWND hwnd,INT id) {
919         FIXME_(keyboard)("(0x%08x,%d): stub\n",hwnd,id);
920         return TRUE;
921 }
922
923 /***********************************************************************
924  *              LoadKeyboardLayoutA (USER32.@)
925  * Call ignored. WINE supports only system default keyboard layout.
926  */
927 HKL WINAPI LoadKeyboardLayoutA(LPCSTR pwszKLID, UINT Flags)
928 {
929     TRACE_(keyboard)("(%s, %d)\n", pwszKLID, Flags);
930     ERR_(keyboard)("Only default system keyboard layout supported. Call ignored.\n");
931   return 0; 
932 }
933
934 /***********************************************************************
935  *              LoadKeyboardLayoutW (USER32.@)
936  */
937 HKL WINAPI LoadKeyboardLayoutW(LPCWSTR pwszKLID, UINT Flags)
938 {
939     char buf[9];
940     
941     WideCharToMultiByte( CP_ACP, 0, pwszKLID, -1, buf, sizeof(buf), NULL, NULL );
942     buf[8] = 0;
943     return LoadKeyboardLayoutA(buf, Flags);
944 }
945
946
947 typedef struct __TRACKINGLIST {
948     TRACKMOUSEEVENT tme;
949     POINT pos; /* center of hover rectangle */
950     INT iHoverTime; /* elapsed time the cursor has been inside of the hover rect */
951 } _TRACKINGLIST; 
952
953 static _TRACKINGLIST TrackingList[10];
954 static int iTrackMax = 0;
955 static UINT_PTR timer;
956 static const INT iTimerInterval = 50; /* msec for timer interval */
957
958 /* FIXME: need to implement WM_NCMOUSELEAVE and WM_NCMOUSEHOVER for */
959 /* TrackMouseEventProc and _TrackMouseEvent */
960 static void CALLBACK TrackMouseEventProc(HWND hwndUnused, UINT uMsg, UINT_PTR idEvent,
961     DWORD dwTime)
962 {
963     int i = 0;
964     POINT pos;
965     HWND hwnd;
966     INT hoverwidth = 0, hoverheight = 0;
967
968     GetCursorPos(&pos);
969     hwnd = WindowFromPoint(pos);
970
971     SystemParametersInfoA(SPI_GETMOUSEHOVERWIDTH, 0, &hoverwidth, 0);
972     SystemParametersInfoA(SPI_GETMOUSEHOVERHEIGHT, 0, &hoverheight, 0);
973
974     /* loop through tracking events we are processing */
975     while (i < iTrackMax) {
976         /* see if this tracking event is looking for TME_LEAVE and that the */
977         /* mouse has left the window */
978         if ((TrackingList[i].tme.dwFlags & TME_LEAVE) &&
979              (TrackingList[i].tme.hwndTrack != hwnd)) {
980             PostMessageA(TrackingList[i].tme.hwndTrack, WM_MOUSELEAVE, 0, 0);
981
982             /* remove the TME_LEAVE flag */
983             TrackingList[i].tme.dwFlags ^= TME_LEAVE;
984         }
985
986         /* see if we are tracking hovering for this hwnd */
987         if(TrackingList[i].tme.dwFlags & TME_HOVER) {
988             /* add the timer interval to the hovering time */
989             TrackingList[i].iHoverTime+=iTimerInterval;  
990      
991             /* has the cursor moved outside the rectangle centered around pos? */
992             if((abs(pos.x - TrackingList[i].pos.x) > (hoverwidth / 2.0))
993               || (abs(pos.y - TrackingList[i].pos.y) > (hoverheight / 2.0)))
994             {
995                 /* record this new position as the current position and reset */
996                 /* the iHoverTime variable to 0 */
997                 TrackingList[i].pos = pos;
998                 TrackingList[i].iHoverTime = 0;
999             }
1000
1001             /* has the mouse hovered long enough? */
1002             if(TrackingList[i].iHoverTime <= TrackingList[i].tme.dwHoverTime)
1003              {
1004                 PostMessageA(TrackingList[i].tme.hwndTrack, WM_MOUSEHOVER, 0, 0);
1005
1006                 /* stop tracking mouse hover */
1007                 TrackingList[i].tme.dwFlags ^= TME_HOVER;
1008             }
1009         }
1010
1011         /* see if we are still tracking TME_HOVER or TME_LEAVE for this entry */
1012         if((TrackingList[i].tme.dwFlags & TME_HOVER) ||
1013            (TrackingList[i].tme.dwFlags & TME_LEAVE)) {
1014             i++;
1015         } else { /* remove this entry from the tracking list */
1016             TrackingList[i] = TrackingList[--iTrackMax];
1017         }
1018     }
1019         
1020     /* stop the timer if the tracking list is empty */
1021     if(iTrackMax == 0) {
1022         KillTimer(0, timer);
1023         timer = 0;
1024     }
1025 }
1026
1027
1028 /***********************************************************************
1029  * TrackMouseEvent [USER32]
1030  *
1031  * Requests notification of mouse events
1032  *
1033  * During mouse tracking WM_MOUSEHOVER or WM_MOUSELEAVE events are posted
1034  * to the hwnd specified in the ptme structure.  After the event message
1035  * is posted to the hwnd, the entry in the queue is removed.
1036  *
1037  * If the current hwnd isn't ptme->hwndTrack the TME_HOVER flag is completely
1038  * ignored. The TME_LEAVE flag results in a WM_MOUSELEAVE message being posted
1039  * immediately and the TME_LEAVE flag being ignored.
1040  *
1041  * PARAMS
1042  *     ptme [I,O] pointer to TRACKMOUSEEVENT information structure.
1043  *
1044  * RETURNS
1045  *     Success: non-zero
1046  *     Failure: zero
1047  *
1048  */
1049
1050 BOOL WINAPI
1051 TrackMouseEvent (TRACKMOUSEEVENT *ptme)
1052 {
1053     DWORD flags = 0;
1054     int i = 0;
1055     BOOL cancel = 0, hover = 0, leave = 0, query = 0;
1056     HWND hwnd;
1057     POINT pos;
1058
1059     pos.x = 0;
1060     pos.y = 0;
1061
1062     TRACE("%lx, %lx, %x, %lx\n", ptme->cbSize, ptme->dwFlags, ptme->hwndTrack, ptme->dwHoverTime);
1063
1064     if (ptme->cbSize != sizeof(TRACKMOUSEEVENT)) {
1065         WARN("wrong TRACKMOUSEEVENT size from app\n");
1066         SetLastError(ERROR_INVALID_PARAMETER); /* FIXME not sure if this is correct */
1067         return FALSE;
1068     }
1069
1070     flags = ptme->dwFlags;
1071     
1072     /* if HOVER_DEFAULT was specified replace this with the systems current value */
1073     if(ptme->dwHoverTime == HOVER_DEFAULT)
1074         SystemParametersInfoA(SPI_GETMOUSEHOVERTIME, 0, &(ptme->dwHoverTime), 0);
1075
1076     GetCursorPos(&pos);
1077     hwnd = WindowFromPoint(pos);    
1078
1079     if ( flags & TME_CANCEL ) {
1080         flags &= ~ TME_CANCEL;
1081         cancel = 1;
1082     }
1083     
1084     if ( flags & TME_HOVER  ) {
1085         flags &= ~ TME_HOVER;
1086         hover = 1;
1087     }
1088     
1089     if ( flags & TME_LEAVE ) {
1090         flags &= ~ TME_LEAVE;
1091         leave = 1;
1092     }
1093
1094     /* fill the TRACKMOUSEEVENT struct with the current tracking for the given hwnd */
1095     if ( flags & TME_QUERY ) {
1096         flags &= ~ TME_QUERY;
1097         query = 1;
1098         i = 0;
1099
1100         /* Find the tracking list entry with the matching hwnd */
1101         while((i < iTrackMax) && (TrackingList[i].tme.hwndTrack != ptme->hwndTrack)) {
1102             i++;
1103         }
1104
1105         /* hwnd found, fill in the ptme struct */
1106         if(i < iTrackMax)
1107             *ptme = TrackingList[i].tme;
1108         else
1109             ptme->dwFlags = 0;
1110     
1111         return TRUE; /* return here, TME_QUERY is retrieving information */
1112     }
1113
1114     if ( flags )
1115         FIXME("Unknown flag(s) %08lx\n", flags );
1116
1117     if(cancel) {
1118         /* find a matching hwnd if one exists */
1119         i = 0;
1120
1121         while((i < iTrackMax) && (TrackingList[i].tme.hwndTrack != ptme->hwndTrack)) {
1122           i++;
1123         }
1124
1125         if(i < iTrackMax) {
1126             TrackingList[i].tme.dwFlags &= ~(ptme->dwFlags & ~TME_CANCEL);
1127
1128             /* if we aren't tracking on hover or leave remove this entry */
1129             if(!((TrackingList[i].tme.dwFlags & TME_HOVER) ||
1130                  (TrackingList[i].tme.dwFlags & TME_LEAVE)))
1131             {
1132                 TrackingList[i] = TrackingList[--iTrackMax];
1133         
1134                 if(iTrackMax == 0) {
1135                     KillTimer(0, timer);
1136                     timer = 0;
1137                 }
1138             }
1139         }
1140     } else {
1141         /* see if hwndTrack isn't the current window */
1142         if(ptme->hwndTrack != hwnd) {
1143             if(leave) {
1144                 PostMessageA(ptme->hwndTrack, WM_MOUSELEAVE, 0, 0);
1145             }
1146         } else {
1147             /* See if this hwnd is already being tracked and update the tracking flags */
1148             for(i = 0; i < iTrackMax; i++) {
1149                 if(TrackingList[i].tme.hwndTrack == ptme->hwndTrack) {
1150                     if(hover) {
1151                         TrackingList[i].tme.dwFlags |= TME_HOVER;
1152                         TrackingList[i].tme.dwHoverTime = ptme->dwHoverTime;
1153                     }
1154  
1155                     if(leave)
1156                         TrackingList[i].tme.dwFlags |= TME_LEAVE;
1157
1158                     /* reset iHoverTime as per winapi specs */
1159                     TrackingList[i].iHoverTime = 0;                  
1160   
1161                     return TRUE;
1162                 }
1163             }           
1164
1165             /* if the tracking list is full return FALSE */
1166             if (iTrackMax == sizeof (TrackingList) / sizeof(*TrackingList)) {
1167                 return FALSE;
1168             }
1169
1170             /* Adding new mouse event to the tracking list */
1171             TrackingList[iTrackMax].tme = *ptme;
1172
1173             /* Initialize HoverInfo variables even if not hover tracking */
1174             TrackingList[iTrackMax].iHoverTime = 0;
1175             TrackingList[iTrackMax].pos = pos;
1176
1177             iTrackMax++;
1178
1179             if (!timer) {
1180                 timer = SetTimer(0, 0, iTimerInterval, TrackMouseEventProc);
1181             }
1182         }
1183     }
1184
1185     return TRUE;
1186 }
1187
1188
1189