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