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