winealsa: Map ALSA errors to AUDCLNT_E_*.
[wine] / dlls / user32 / 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 "ntstatus.h"
38 #define WIN32_NO_STATUS
39 #include "windef.h"
40 #include "winbase.h"
41 #include "wingdi.h"
42 #include "winuser.h"
43 #include "winnls.h"
44 #include "winternl.h"
45 #include "winerror.h"
46 #include "win.h"
47 #include "user_private.h"
48 #include "wine/server.h"
49 #include "wine/debug.h"
50 #include "wine/unicode.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(win);
53 WINE_DECLARE_DEBUG_CHANNEL(keyboard);
54
55
56 /***********************************************************************
57  *           get_key_state
58  */
59 static WORD get_key_state(void)
60 {
61     WORD ret = 0;
62
63     if (GetSystemMetrics( SM_SWAPBUTTON ))
64     {
65         if (GetAsyncKeyState(VK_RBUTTON) & 0x80) ret |= MK_LBUTTON;
66         if (GetAsyncKeyState(VK_LBUTTON) & 0x80) ret |= MK_RBUTTON;
67     }
68     else
69     {
70         if (GetAsyncKeyState(VK_LBUTTON) & 0x80) ret |= MK_LBUTTON;
71         if (GetAsyncKeyState(VK_RBUTTON) & 0x80) ret |= MK_RBUTTON;
72     }
73     if (GetAsyncKeyState(VK_MBUTTON) & 0x80)  ret |= MK_MBUTTON;
74     if (GetAsyncKeyState(VK_SHIFT) & 0x80)    ret |= MK_SHIFT;
75     if (GetAsyncKeyState(VK_CONTROL) & 0x80)  ret |= MK_CONTROL;
76     if (GetAsyncKeyState(VK_XBUTTON1) & 0x80) ret |= MK_XBUTTON1;
77     if (GetAsyncKeyState(VK_XBUTTON2) & 0x80) ret |= MK_XBUTTON2;
78     return ret;
79 }
80
81
82 /**********************************************************************
83  *              set_capture_window
84  */
85 BOOL set_capture_window( HWND hwnd, UINT gui_flags, HWND *prev_ret )
86 {
87     HWND previous = 0;
88     UINT flags = 0;
89     BOOL ret;
90
91     if (gui_flags & GUI_INMENUMODE) flags |= CAPTURE_MENU;
92     if (gui_flags & GUI_INMOVESIZE) flags |= CAPTURE_MOVESIZE;
93
94     SERVER_START_REQ( set_capture_window )
95     {
96         req->handle = wine_server_user_handle( hwnd );
97         req->flags  = flags;
98         if ((ret = !wine_server_call_err( req )))
99         {
100             previous = wine_server_ptr_handle( reply->previous );
101             hwnd = wine_server_ptr_handle( reply->full_handle );
102         }
103     }
104     SERVER_END_REQ;
105
106     if (ret)
107     {
108         USER_Driver->pSetCapture( hwnd, gui_flags );
109
110         if (previous && previous != hwnd)
111             SendMessageW( previous, WM_CAPTURECHANGED, 0, (LPARAM)hwnd );
112
113         if (prev_ret) *prev_ret = previous;
114     }
115     return ret;
116 }
117
118
119 /***********************************************************************
120  *              __wine_send_input  (USER32.@)
121  *
122  * Internal SendInput function to allow the graphics driver to inject real events.
123  */
124 BOOL CDECL __wine_send_input( HWND hwnd, const INPUT *input )
125 {
126     NTSTATUS status = send_hardware_message( hwnd, input, 0 );
127     if (status) SetLastError( RtlNtStatusToDosError(status) );
128     return !status;
129 }
130
131
132 /***********************************************************************
133  *              update_mouse_coords
134  *
135  * Helper for SendInput.
136  */
137 static void update_mouse_coords( INPUT *input )
138 {
139     if (!(input->u.mi.dwFlags & MOUSEEVENTF_MOVE)) return;
140
141     if (input->u.mi.dwFlags & MOUSEEVENTF_ABSOLUTE)
142     {
143         input->u.mi.dx = (input->u.mi.dx * GetSystemMetrics( SM_CXSCREEN )) >> 16;
144         input->u.mi.dy = (input->u.mi.dy * GetSystemMetrics( SM_CYSCREEN )) >> 16;
145     }
146     else
147     {
148         int accel[3];
149
150         /* dx and dy can be negative numbers for relative movements */
151         SystemParametersInfoW(SPI_GETMOUSE, 0, accel, 0);
152
153         if (!accel[2]) return;
154
155         if (abs(input->u.mi.dx) > accel[0])
156         {
157             input->u.mi.dx *= 2;
158             if ((abs(input->u.mi.dx) > accel[1]) && (accel[2] == 2)) input->u.mi.dx *= 2;
159         }
160         if (abs(input->u.mi.dy) > accel[0])
161         {
162             input->u.mi.dy *= 2;
163             if ((abs(input->u.mi.dy) > accel[1]) && (accel[2] == 2)) input->u.mi.dy *= 2;
164         }
165     }
166 }
167
168 /***********************************************************************
169  *              SendInput  (USER32.@)
170  */
171 UINT WINAPI SendInput( UINT count, LPINPUT inputs, int size )
172 {
173     UINT i;
174     NTSTATUS status;
175
176     for (i = 0; i < count; i++)
177     {
178         if (inputs[i].type == INPUT_MOUSE)
179         {
180             /* we need to update the coordinates to what the server expects */
181             INPUT input = inputs[i];
182             update_mouse_coords( &input );
183             status = send_hardware_message( 0, &input, SEND_HWMSG_INJECTED );
184         }
185         else status = send_hardware_message( 0, &inputs[i], SEND_HWMSG_INJECTED );
186
187         if (status)
188         {
189             SetLastError( RtlNtStatusToDosError(status) );
190             break;
191         }
192     }
193
194     return i;
195 }
196
197
198 /***********************************************************************
199  *              keybd_event (USER32.@)
200  */
201 void WINAPI keybd_event( BYTE bVk, BYTE bScan,
202                          DWORD dwFlags, ULONG_PTR dwExtraInfo )
203 {
204     INPUT input;
205
206     input.type = INPUT_KEYBOARD;
207     input.u.ki.wVk = bVk;
208     input.u.ki.wScan = bScan;
209     input.u.ki.dwFlags = dwFlags;
210     input.u.ki.time = 0;
211     input.u.ki.dwExtraInfo = dwExtraInfo;
212     SendInput( 1, &input, sizeof(input) );
213 }
214
215
216 /***********************************************************************
217  *              mouse_event (USER32.@)
218  */
219 void WINAPI mouse_event( DWORD dwFlags, DWORD dx, DWORD dy,
220                          DWORD dwData, ULONG_PTR dwExtraInfo )
221 {
222     INPUT input;
223
224     input.type = INPUT_MOUSE;
225     input.u.mi.dx = dx;
226     input.u.mi.dy = dy;
227     input.u.mi.mouseData = dwData;
228     input.u.mi.dwFlags = dwFlags;
229     input.u.mi.time = 0;
230     input.u.mi.dwExtraInfo = dwExtraInfo;
231     SendInput( 1, &input, sizeof(input) );
232 }
233
234
235 /***********************************************************************
236  *              GetCursorPos (USER32.@)
237  */
238 BOOL WINAPI DECLSPEC_HOTPATCH GetCursorPos( POINT *pt )
239 {
240     BOOL ret;
241     DWORD last_change;
242
243     if (!pt) return FALSE;
244
245     SERVER_START_REQ( set_cursor )
246     {
247         if ((ret = !wine_server_call( req )))
248         {
249             pt->x = reply->new_x;
250             pt->y = reply->new_y;
251             last_change = reply->last_change;
252         }
253     }
254     SERVER_END_REQ;
255
256     /* query new position from graphics driver if we haven't updated recently */
257     if (ret && GetTickCount() - last_change > 100) ret = USER_Driver->pGetCursorPos( pt );
258     return ret;
259 }
260
261
262 /***********************************************************************
263  *              GetCursorInfo (USER32.@)
264  */
265 BOOL WINAPI GetCursorInfo( PCURSORINFO pci )
266 {
267     BOOL ret;
268
269     if (!pci) return 0;
270
271     SERVER_START_REQ( get_thread_input )
272     {
273         req->tid = 0;
274         if ((ret = !wine_server_call( req )))
275         {
276             pci->hCursor = wine_server_ptr_handle( reply->cursor );
277             pci->flags = (reply->show_count >= 0) ? CURSOR_SHOWING : 0;
278         }
279     }
280     SERVER_END_REQ;
281     GetCursorPos(&pci->ptScreenPos);
282     return ret;
283 }
284
285
286 /***********************************************************************
287  *              SetCursorPos (USER32.@)
288  */
289 BOOL WINAPI DECLSPEC_HOTPATCH SetCursorPos( INT x, INT y )
290 {
291     BOOL ret;
292     INT prev_x, prev_y, new_x, new_y;
293
294     SERVER_START_REQ( set_cursor )
295     {
296         req->flags = SET_CURSOR_POS;
297         req->x     = x;
298         req->y     = y;
299         if ((ret = !wine_server_call( req )))
300         {
301             prev_x = reply->prev_x;
302             prev_y = reply->prev_y;
303             new_x  = reply->new_x;
304             new_y  = reply->new_y;
305         }
306     }
307     SERVER_END_REQ;
308     if (ret && (prev_x != new_x || prev_y != new_y)) USER_Driver->pSetCursorPos( new_x, new_y );
309     return ret;
310 }
311
312
313 /**********************************************************************
314  *              SetCapture (USER32.@)
315  */
316 HWND WINAPI DECLSPEC_HOTPATCH SetCapture( HWND hwnd )
317 {
318     HWND previous = 0;
319
320     set_capture_window( hwnd, 0, &previous );
321     return previous;
322 }
323
324
325 /**********************************************************************
326  *              ReleaseCapture (USER32.@)
327  */
328 BOOL WINAPI DECLSPEC_HOTPATCH ReleaseCapture(void)
329 {
330     BOOL ret = set_capture_window( 0, 0, NULL );
331
332     /* Somebody may have missed some mouse movements */
333     if (ret) mouse_event( MOUSEEVENTF_MOVE, 0, 0, 0, 0 );
334
335     return ret;
336 }
337
338
339 /**********************************************************************
340  *              GetCapture (USER32.@)
341  */
342 HWND WINAPI GetCapture(void)
343 {
344     HWND ret = 0;
345
346     SERVER_START_REQ( get_thread_input )
347     {
348         req->tid = GetCurrentThreadId();
349         if (!wine_server_call_err( req )) ret = wine_server_ptr_handle( reply->capture );
350     }
351     SERVER_END_REQ;
352     return ret;
353 }
354
355
356 /**********************************************************************
357  *              GetAsyncKeyState (USER32.@)
358  *
359  *      Determine if a key is or was pressed.  retval has high-order
360  * bit set to 1 if currently pressed, low-order bit set to 1 if key has
361  * been pressed.
362  */
363 SHORT WINAPI DECLSPEC_HOTPATCH GetAsyncKeyState( INT key )
364 {
365     struct user_thread_info *thread_info = get_user_thread_info();
366     SHORT ret;
367
368     if (key < 0 || key >= 256) return 0;
369
370     if ((ret = USER_Driver->pGetAsyncKeyState( key )) == -1)
371     {
372         if (thread_info->key_state &&
373             !(thread_info->key_state[key] & 0xc0) &&
374             GetTickCount() - thread_info->key_state_time < 50)
375             return 0;
376
377         if (!thread_info->key_state) thread_info->key_state = HeapAlloc( GetProcessHeap(), 0, 256 );
378
379         ret = 0;
380         SERVER_START_REQ( get_key_state )
381         {
382             req->tid = 0;
383             req->key = key;
384             if (thread_info->key_state) wine_server_set_reply( req, thread_info->key_state, 256 );
385             if (!wine_server_call( req ))
386             {
387                 if (reply->state & 0x40) ret |= 0x0001;
388                 if (reply->state & 0x80) ret |= 0x8000;
389                 thread_info->key_state_time = GetTickCount();
390             }
391         }
392         SERVER_END_REQ;
393     }
394     return ret;
395 }
396
397
398 /***********************************************************************
399  *              GetQueueStatus (USER32.@)
400  */
401 DWORD WINAPI GetQueueStatus( UINT flags )
402 {
403     DWORD ret = 0;
404
405     if (flags & ~(QS_ALLINPUT | QS_ALLPOSTMESSAGE | QS_SMRESULT))
406     {
407         SetLastError( ERROR_INVALID_FLAGS );
408         return 0;
409     }
410
411     /* check for pending X events */
412     USER_Driver->pMsgWaitForMultipleObjectsEx( 0, NULL, 0, flags, 0 );
413
414     SERVER_START_REQ( get_queue_status )
415     {
416         req->clear = 1;
417         wine_server_call( req );
418         ret = MAKELONG( reply->changed_bits & flags, reply->wake_bits & flags );
419     }
420     SERVER_END_REQ;
421     return ret;
422 }
423
424
425 /***********************************************************************
426  *              GetInputState   (USER32.@)
427  */
428 BOOL WINAPI GetInputState(void)
429 {
430     DWORD ret = 0;
431
432     /* check for pending X events */
433     USER_Driver->pMsgWaitForMultipleObjectsEx( 0, NULL, 0, QS_INPUT, 0 );
434
435     SERVER_START_REQ( get_queue_status )
436     {
437         req->clear = 0;
438         wine_server_call( req );
439         ret = reply->wake_bits & (QS_KEY | QS_MOUSEBUTTON);
440     }
441     SERVER_END_REQ;
442     return ret;
443 }
444
445
446 /******************************************************************
447  *              GetLastInputInfo (USER32.@)
448  */
449 BOOL WINAPI GetLastInputInfo(PLASTINPUTINFO plii)
450 {
451     BOOL ret;
452
453     TRACE("%p\n", plii);
454
455     if (plii->cbSize != sizeof (*plii) )
456     {
457         SetLastError(ERROR_INVALID_PARAMETER);
458         return FALSE;
459     }
460
461     SERVER_START_REQ( get_last_input_time )
462     {
463         ret = !wine_server_call_err( req );
464         if (ret)
465             plii->dwTime = reply->time;
466     }
467     SERVER_END_REQ;
468     return ret;
469 }
470
471
472 /******************************************************************
473 *               GetRawInputDeviceList (USER32.@)
474 */
475 UINT WINAPI GetRawInputDeviceList(PRAWINPUTDEVICELIST pRawInputDeviceList, PUINT puiNumDevices, UINT cbSize)
476 {
477     FIXME("(pRawInputDeviceList=%p, puiNumDevices=%p, cbSize=%d) stub!\n", pRawInputDeviceList, puiNumDevices, cbSize);
478
479     if(pRawInputDeviceList)
480         memset(pRawInputDeviceList, 0, sizeof *pRawInputDeviceList);
481     *puiNumDevices = 0;
482     return 0;
483 }
484
485
486 /******************************************************************
487 *               RegisterRawInputDevices (USER32.@)
488 */
489 BOOL WINAPI DECLSPEC_HOTPATCH RegisterRawInputDevices(PRAWINPUTDEVICE pRawInputDevices, UINT uiNumDevices, UINT cbSize)
490 {
491     FIXME("(pRawInputDevices=%p, uiNumDevices=%d, cbSize=%d) stub!\n", pRawInputDevices, uiNumDevices, cbSize);
492
493     return TRUE;
494 }
495
496
497 /******************************************************************
498 *               GetRawInputData (USER32.@)
499 */
500 UINT WINAPI GetRawInputData(HRAWINPUT hRawInput, UINT uiCommand, LPVOID pData, PUINT pcbSize, UINT cbSizeHeader)
501 {
502     FIXME("(hRawInput=%p, uiCommand=%d, pData=%p, pcbSize=%p, cbSizeHeader=%d) stub!\n",
503             hRawInput, uiCommand, pData, pcbSize, cbSizeHeader);
504
505     return 0;
506 }
507
508
509 /******************************************************************
510 *               GetRawInputBuffer (USER32.@)
511 */
512 UINT WINAPI DECLSPEC_HOTPATCH GetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT cbSizeHeader)
513 {
514     FIXME("(pData=%p, pcbSize=%p, cbSizeHeader=%d) stub!\n", pData, pcbSize, cbSizeHeader);
515
516     return 0;
517 }
518
519
520 /******************************************************************
521 *               GetRawInputDeviceInfoA (USER32.@)
522 */
523 UINT WINAPI GetRawInputDeviceInfoA(HANDLE hDevice, UINT uiCommand, LPVOID pData, PUINT pcbSize)
524 {
525     FIXME("(hDevice=%p, uiCommand=%d, pData=%p, pcbSize=%p) stub!\n", hDevice, uiCommand, pData, pcbSize);
526
527     return 0;
528 }
529
530
531 /******************************************************************
532 *               GetRawInputDeviceInfoW (USER32.@)
533 */
534 UINT WINAPI GetRawInputDeviceInfoW(HANDLE hDevice, UINT uiCommand, LPVOID pData, PUINT pcbSize)
535 {
536     FIXME("(hDevice=%p, uiCommand=%d, pData=%p, pcbSize=%p) stub!\n", hDevice, uiCommand, pData, pcbSize);
537
538     return 0;
539 }
540
541
542 /******************************************************************
543 *               GetRegisteredRawInputDevices (USER32.@)
544 */
545 UINT WINAPI GetRegisteredRawInputDevices(PRAWINPUTDEVICE pRawInputDevices, PUINT puiNumDevices, UINT cbSize)
546 {
547     FIXME("(pRawInputDevices=%p, puiNumDevices=%p, cbSize=%d) stub!\n", pRawInputDevices, puiNumDevices, cbSize);
548
549     return 0;
550 }
551
552
553 /******************************************************************
554 *               DefRawInputProc (USER32.@)
555 */
556 LRESULT WINAPI DefRawInputProc(PRAWINPUT *paRawInput, INT nInput, UINT cbSizeHeader)
557 {
558     FIXME("(paRawInput=%p, nInput=%d, cbSizeHeader=%d) stub!\n", *paRawInput, nInput, cbSizeHeader);
559
560     return 0;
561 }
562
563
564 /**********************************************************************
565  *              AttachThreadInput (USER32.@)
566  *
567  * Attaches the input processing mechanism of one thread to that of
568  * another thread.
569  */
570 BOOL WINAPI AttachThreadInput( DWORD from, DWORD to, BOOL attach )
571 {
572     BOOL ret;
573
574     SERVER_START_REQ( attach_thread_input )
575     {
576         req->tid_from = from;
577         req->tid_to   = to;
578         req->attach   = attach;
579         ret = !wine_server_call_err( req );
580     }
581     SERVER_END_REQ;
582     return ret;
583 }
584
585
586 /**********************************************************************
587  *              GetKeyState (USER32.@)
588  *
589  * An application calls the GetKeyState function in response to a
590  * keyboard-input message.  This function retrieves the state of the key
591  * at the time the input message was generated.
592  */
593 SHORT WINAPI DECLSPEC_HOTPATCH GetKeyState(INT vkey)
594 {
595     SHORT retval = 0;
596
597     SERVER_START_REQ( get_key_state )
598     {
599         req->tid = GetCurrentThreadId();
600         req->key = vkey;
601         if (!wine_server_call( req )) retval = (signed char)reply->state;
602     }
603     SERVER_END_REQ;
604     TRACE("key (0x%x) -> %x\n", vkey, retval);
605     return retval;
606 }
607
608
609 /**********************************************************************
610  *              GetKeyboardState (USER32.@)
611  */
612 BOOL WINAPI DECLSPEC_HOTPATCH GetKeyboardState( LPBYTE state )
613 {
614     BOOL ret;
615
616     TRACE("(%p)\n", state);
617
618     memset( state, 0, 256 );
619     SERVER_START_REQ( get_key_state )
620     {
621         req->tid = GetCurrentThreadId();
622         req->key = -1;
623         wine_server_set_reply( req, state, 256 );
624         ret = !wine_server_call_err( req );
625     }
626     SERVER_END_REQ;
627     return ret;
628 }
629
630
631 /**********************************************************************
632  *              SetKeyboardState (USER32.@)
633  */
634 BOOL WINAPI SetKeyboardState( LPBYTE state )
635 {
636     BOOL ret;
637
638     SERVER_START_REQ( set_key_state )
639     {
640         req->tid = GetCurrentThreadId();
641         wine_server_add_data( req, state, 256 );
642         ret = !wine_server_call_err( req );
643     }
644     SERVER_END_REQ;
645     return ret;
646 }
647
648
649 /**********************************************************************
650  *              VkKeyScanA (USER32.@)
651  *
652  * VkKeyScan translates an ANSI character to a virtual-key and shift code
653  * for the current keyboard.
654  * high-order byte yields :
655  *      0       Unshifted
656  *      1       Shift
657  *      2       Ctrl
658  *      3-5     Shift-key combinations that are not used for characters
659  *      6       Ctrl-Alt
660  *      7       Ctrl-Alt-Shift
661  *      I.e. :  Shift = 1, Ctrl = 2, Alt = 4.
662  * FIXME : works ok except for dead chars :
663  * VkKeyScan '^'(0x5e, 94) ... got keycode 00 ... returning 00
664  * VkKeyScan '`'(0x60, 96) ... got keycode 00 ... returning 00
665  */
666 SHORT WINAPI VkKeyScanA(CHAR cChar)
667 {
668     WCHAR wChar;
669
670     if (IsDBCSLeadByte(cChar)) return -1;
671
672     MultiByteToWideChar(CP_ACP, 0, &cChar, 1, &wChar, 1);
673     return VkKeyScanW(wChar);
674 }
675
676 /******************************************************************************
677  *              VkKeyScanW (USER32.@)
678  */
679 SHORT WINAPI VkKeyScanW(WCHAR cChar)
680 {
681     return VkKeyScanExW(cChar, GetKeyboardLayout(0));
682 }
683
684 /**********************************************************************
685  *              VkKeyScanExA (USER32.@)
686  */
687 WORD WINAPI VkKeyScanExA(CHAR cChar, HKL dwhkl)
688 {
689     WCHAR wChar;
690
691     if (IsDBCSLeadByte(cChar)) return -1;
692
693     MultiByteToWideChar(CP_ACP, 0, &cChar, 1, &wChar, 1);
694     return VkKeyScanExW(wChar, dwhkl);
695 }
696
697 /******************************************************************************
698  *              VkKeyScanExW (USER32.@)
699  */
700 WORD WINAPI VkKeyScanExW(WCHAR cChar, HKL dwhkl)
701 {
702     return USER_Driver->pVkKeyScanEx(cChar, dwhkl);
703 }
704
705 /**********************************************************************
706  *              OemKeyScan (USER32.@)
707  */
708 DWORD WINAPI OemKeyScan(WORD wOemChar)
709 {
710     return wOemChar;
711 }
712
713 /******************************************************************************
714  *              GetKeyboardType (USER32.@)
715  */
716 INT WINAPI GetKeyboardType(INT nTypeFlag)
717 {
718     TRACE_(keyboard)("(%d)\n", nTypeFlag);
719     switch(nTypeFlag)
720     {
721     case 0:      /* Keyboard type */
722         return 4;    /* AT-101 */
723     case 1:      /* Keyboard Subtype */
724         return 0;    /* There are no defined subtypes */
725     case 2:      /* Number of F-keys */
726         return 12;   /* We're doing an 101 for now, so return 12 F-keys */
727     default:
728         WARN_(keyboard)("Unknown type\n");
729         return 0;    /* The book says 0 here, so 0 */
730     }
731 }
732
733 /******************************************************************************
734  *              MapVirtualKeyA (USER32.@)
735  */
736 UINT WINAPI MapVirtualKeyA(UINT code, UINT maptype)
737 {
738     return MapVirtualKeyExA( code, maptype, GetKeyboardLayout(0) );
739 }
740
741 /******************************************************************************
742  *              MapVirtualKeyW (USER32.@)
743  */
744 UINT WINAPI MapVirtualKeyW(UINT code, UINT maptype)
745 {
746     return MapVirtualKeyExW(code, maptype, GetKeyboardLayout(0));
747 }
748
749 /******************************************************************************
750  *              MapVirtualKeyExA (USER32.@)
751  */
752 UINT WINAPI MapVirtualKeyExA(UINT code, UINT maptype, HKL hkl)
753 {
754     UINT ret;
755
756     ret = MapVirtualKeyExW( code, maptype, hkl );
757     if (maptype == MAPVK_VK_TO_CHAR)
758     {
759         BYTE ch = 0;
760         WCHAR wch = ret;
761
762         WideCharToMultiByte( CP_ACP, 0, &wch, 1, (LPSTR)&ch, 1, NULL, NULL );
763         ret = ch;
764     }
765     return ret;
766 }
767
768 /******************************************************************************
769  *              MapVirtualKeyExW (USER32.@)
770  */
771 UINT WINAPI MapVirtualKeyExW(UINT code, UINT maptype, HKL hkl)
772 {
773     TRACE_(keyboard)("(%X, %d, %p)\n", code, maptype, hkl);
774
775     return USER_Driver->pMapVirtualKeyEx(code, maptype, hkl);
776 }
777
778 /****************************************************************************
779  *              GetKBCodePage (USER32.@)
780  */
781 UINT WINAPI GetKBCodePage(void)
782 {
783     return GetOEMCP();
784 }
785
786 /***********************************************************************
787  *              GetKeyboardLayout (USER32.@)
788  *
789  *        - device handle for keyboard layout defaulted to
790  *          the language id. This is the way Windows default works.
791  *        - the thread identifier is also ignored.
792  */
793 HKL WINAPI GetKeyboardLayout(DWORD thread_id)
794 {
795     return USER_Driver->pGetKeyboardLayout(thread_id);
796 }
797
798 /****************************************************************************
799  *              GetKeyboardLayoutNameA (USER32.@)
800  */
801 BOOL WINAPI GetKeyboardLayoutNameA(LPSTR pszKLID)
802 {
803     WCHAR buf[KL_NAMELENGTH];
804
805     if (GetKeyboardLayoutNameW(buf))
806         return WideCharToMultiByte( CP_ACP, 0, buf, -1, pszKLID, KL_NAMELENGTH, NULL, NULL ) != 0;
807     return FALSE;
808 }
809
810 /****************************************************************************
811  *              GetKeyboardLayoutNameW (USER32.@)
812  */
813 BOOL WINAPI GetKeyboardLayoutNameW(LPWSTR pwszKLID)
814 {
815     return USER_Driver->pGetKeyboardLayoutName(pwszKLID);
816 }
817
818 /****************************************************************************
819  *              GetKeyNameTextA (USER32.@)
820  */
821 INT WINAPI GetKeyNameTextA(LONG lParam, LPSTR lpBuffer, INT nSize)
822 {
823     WCHAR buf[256];
824     INT ret;
825
826     if (!GetKeyNameTextW(lParam, buf, 256))
827     {
828         lpBuffer[0] = 0;
829         return 0;
830     }
831     ret = WideCharToMultiByte(CP_ACP, 0, buf, -1, lpBuffer, nSize, NULL, NULL);
832     if (!ret && nSize)
833     {
834         ret = nSize - 1;
835         lpBuffer[ret] = 0;
836     }
837     return ret;
838 }
839
840 /****************************************************************************
841  *              GetKeyNameTextW (USER32.@)
842  */
843 INT WINAPI GetKeyNameTextW(LONG lParam, LPWSTR lpBuffer, INT nSize)
844 {
845     return USER_Driver->pGetKeyNameText( lParam, lpBuffer, nSize );
846 }
847
848 /****************************************************************************
849  *              ToUnicode (USER32.@)
850  */
851 INT WINAPI ToUnicode(UINT virtKey, UINT scanCode, const BYTE *lpKeyState,
852                      LPWSTR lpwStr, int size, UINT flags)
853 {
854     return ToUnicodeEx(virtKey, scanCode, lpKeyState, lpwStr, size, flags, GetKeyboardLayout(0));
855 }
856
857 /****************************************************************************
858  *              ToUnicodeEx (USER32.@)
859  */
860 INT WINAPI ToUnicodeEx(UINT virtKey, UINT scanCode, const BYTE *lpKeyState,
861                        LPWSTR lpwStr, int size, UINT flags, HKL hkl)
862 {
863     return USER_Driver->pToUnicodeEx(virtKey, scanCode, lpKeyState, lpwStr, size, flags, hkl);
864 }
865
866 /****************************************************************************
867  *              ToAscii (USER32.@)
868  */
869 INT WINAPI ToAscii( UINT virtKey, UINT scanCode, const BYTE *lpKeyState,
870                     LPWORD lpChar, UINT flags )
871 {
872     return ToAsciiEx(virtKey, scanCode, lpKeyState, lpChar, flags, GetKeyboardLayout(0));
873 }
874
875 /****************************************************************************
876  *              ToAsciiEx (USER32.@)
877  */
878 INT WINAPI ToAsciiEx( UINT virtKey, UINT scanCode, const BYTE *lpKeyState,
879                       LPWORD lpChar, UINT flags, HKL dwhkl )
880 {
881     WCHAR uni_chars[2];
882     INT ret, n_ret;
883
884     ret = ToUnicodeEx(virtKey, scanCode, lpKeyState, uni_chars, 2, flags, dwhkl);
885     if (ret < 0) n_ret = 1; /* FIXME: make ToUnicode return 2 for dead chars */
886     else n_ret = ret;
887     WideCharToMultiByte(CP_ACP, 0, uni_chars, n_ret, (LPSTR)lpChar, 2, NULL, NULL);
888     return ret;
889 }
890
891 /**********************************************************************
892  *              ActivateKeyboardLayout (USER32.@)
893  */
894 HKL WINAPI ActivateKeyboardLayout(HKL hLayout, UINT flags)
895 {
896     TRACE_(keyboard)("(%p, %d)\n", hLayout, flags);
897
898     return USER_Driver->pActivateKeyboardLayout(hLayout, flags);
899 }
900
901 /**********************************************************************
902  *              BlockInput (USER32.@)
903  */
904 BOOL WINAPI BlockInput(BOOL fBlockIt)
905 {
906     FIXME_(keyboard)("(%d): stub\n", fBlockIt);
907     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
908
909     return FALSE;
910 }
911
912 /***********************************************************************
913  *              GetKeyboardLayoutList (USER32.@)
914  *
915  * Return number of values available if either input parm is
916  *  0, per MS documentation.
917  */
918 UINT WINAPI GetKeyboardLayoutList(INT nBuff, HKL *layouts)
919 {
920     HKEY hKeyKeyboard;
921     DWORD rc;
922     INT count = 0;
923     ULONG_PTR baselayout;
924     LANGID langid;
925     static const WCHAR szKeyboardReg[] = {'S','y','s','t','e','m','\\','C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\','C','o','n','t','r','o','l','\\','K','e','y','b','o','a','r','d',' ','L','a','y','o','u','t','s',0};
926
927     TRACE_(keyboard)("(%d,%p)\n",nBuff,layouts);
928
929     baselayout = GetUserDefaultLCID();
930     langid = PRIMARYLANGID(LANGIDFROMLCID(baselayout));
931     if (langid == LANG_CHINESE || langid == LANG_JAPANESE || langid == LANG_KOREAN)
932         baselayout |= 0xe001 << 16; /* IME */
933     else
934         baselayout |= baselayout << 16;
935
936     /* Enumerate the Registry */
937     rc = RegOpenKeyW(HKEY_LOCAL_MACHINE,szKeyboardReg,&hKeyKeyboard);
938     if (rc == ERROR_SUCCESS)
939     {
940         do {
941             WCHAR szKeyName[9];
942             HKL layout;
943             rc = RegEnumKeyW(hKeyKeyboard, count, szKeyName, 9);
944             if (rc == ERROR_SUCCESS)
945             {
946                 layout = (HKL)(ULONG_PTR)strtoulW(szKeyName,NULL,16);
947                 if (baselayout != 0 && layout == (HKL)baselayout)
948                     baselayout = 0; /* found in the registry do not add again */
949                 if (nBuff && layouts)
950                 {
951                     if (count >= nBuff ) break;
952                     layouts[count] = layout;
953                 }
954                 count ++;
955             }
956         } while (rc == ERROR_SUCCESS);
957         RegCloseKey(hKeyKeyboard);
958     }
959
960     /* make sure our base layout is on the list */
961     if (baselayout != 0)
962     {
963         if (nBuff && layouts)
964         {
965             if (count < nBuff)
966             {
967                 layouts[count] = (HKL)baselayout;
968                 count++;
969             }
970         }
971         else
972             count++;
973     }
974
975     return count;
976 }
977
978
979 /***********************************************************************
980  *              RegisterHotKey (USER32.@)
981  */
982 BOOL WINAPI RegisterHotKey(HWND hwnd,INT id,UINT modifiers,UINT vk)
983 {
984     BOOL ret;
985     int replaced=0;
986
987     TRACE_(keyboard)("(%p,%d,0x%08x,%X)\n",hwnd,id,modifiers,vk);
988
989     if ((hwnd == NULL || WIN_IsCurrentThread(hwnd)) &&
990         !USER_Driver->pRegisterHotKey(hwnd, modifiers, vk))
991         return FALSE;
992
993     SERVER_START_REQ( register_hotkey )
994     {
995         req->window = wine_server_user_handle( hwnd );
996         req->id = id;
997         req->flags = modifiers;
998         req->vkey = vk;
999         if ((ret = !wine_server_call_err( req )))
1000         {
1001             replaced = reply->replaced;
1002             modifiers = reply->flags;
1003             vk = reply->vkey;
1004         }
1005     }
1006     SERVER_END_REQ;
1007
1008     if (ret && replaced)
1009         USER_Driver->pUnregisterHotKey(hwnd, modifiers, vk);
1010
1011     return ret;
1012 }
1013
1014 /***********************************************************************
1015  *              UnregisterHotKey (USER32.@)
1016  */
1017 BOOL WINAPI UnregisterHotKey(HWND hwnd,INT id)
1018 {
1019     BOOL ret;
1020     UINT modifiers, vk;
1021
1022     TRACE_(keyboard)("(%p,%d)\n",hwnd,id);
1023
1024     SERVER_START_REQ( unregister_hotkey )
1025     {
1026         req->window = wine_server_user_handle( hwnd );
1027         req->id = id;
1028         if ((ret = !wine_server_call_err( req )))
1029         {
1030             modifiers = reply->flags;
1031             vk = reply->vkey;
1032         }
1033     }
1034     SERVER_END_REQ;
1035
1036     if (ret)
1037         USER_Driver->pUnregisterHotKey(hwnd, modifiers, vk);
1038
1039     return ret;
1040 }
1041
1042 /***********************************************************************
1043  *              LoadKeyboardLayoutW (USER32.@)
1044  */
1045 HKL WINAPI LoadKeyboardLayoutW(LPCWSTR pwszKLID, UINT Flags)
1046 {
1047     TRACE_(keyboard)("(%s, %d)\n", debugstr_w(pwszKLID), Flags);
1048
1049     return USER_Driver->pLoadKeyboardLayout(pwszKLID, Flags);
1050 }
1051
1052 /***********************************************************************
1053  *              LoadKeyboardLayoutA (USER32.@)
1054  */
1055 HKL WINAPI LoadKeyboardLayoutA(LPCSTR pwszKLID, UINT Flags)
1056 {
1057     HKL ret;
1058     UNICODE_STRING pwszKLIDW;
1059
1060     if (pwszKLID) RtlCreateUnicodeStringFromAsciiz(&pwszKLIDW, pwszKLID);
1061     else pwszKLIDW.Buffer = NULL;
1062
1063     ret = LoadKeyboardLayoutW(pwszKLIDW.Buffer, Flags);
1064     RtlFreeUnicodeString(&pwszKLIDW);
1065     return ret;
1066 }
1067
1068
1069 /***********************************************************************
1070  *              UnloadKeyboardLayout (USER32.@)
1071  */
1072 BOOL WINAPI UnloadKeyboardLayout(HKL hkl)
1073 {
1074     TRACE_(keyboard)("(%p)\n", hkl);
1075
1076     return USER_Driver->pUnloadKeyboardLayout(hkl);
1077 }
1078
1079 typedef struct __TRACKINGLIST {
1080     TRACKMOUSEEVENT tme;
1081     POINT pos; /* center of hover rectangle */
1082 } _TRACKINGLIST;
1083
1084 /* FIXME: move tracking stuff into a per thread data */
1085 static _TRACKINGLIST tracking_info;
1086 static UINT_PTR timer;
1087
1088 static void check_mouse_leave(HWND hwnd, int hittest)
1089 {
1090     if (tracking_info.tme.hwndTrack != hwnd)
1091     {
1092         if (tracking_info.tme.dwFlags & TME_NONCLIENT)
1093             PostMessageW(tracking_info.tme.hwndTrack, WM_NCMOUSELEAVE, 0, 0);
1094         else
1095             PostMessageW(tracking_info.tme.hwndTrack, WM_MOUSELEAVE, 0, 0);
1096
1097         /* remove the TME_LEAVE flag */
1098         tracking_info.tme.dwFlags &= ~TME_LEAVE;
1099     }
1100     else
1101     {
1102         if (hittest == HTCLIENT)
1103         {
1104             if (tracking_info.tme.dwFlags & TME_NONCLIENT)
1105             {
1106                 PostMessageW(tracking_info.tme.hwndTrack, WM_NCMOUSELEAVE, 0, 0);
1107                 /* remove the TME_LEAVE flag */
1108                 tracking_info.tme.dwFlags &= ~TME_LEAVE;
1109             }
1110         }
1111         else
1112         {
1113             if (!(tracking_info.tme.dwFlags & TME_NONCLIENT))
1114             {
1115                 PostMessageW(tracking_info.tme.hwndTrack, WM_MOUSELEAVE, 0, 0);
1116                 /* remove the TME_LEAVE flag */
1117                 tracking_info.tme.dwFlags &= ~TME_LEAVE;
1118             }
1119         }
1120     }
1121 }
1122
1123 static void CALLBACK TrackMouseEventProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent,
1124                                          DWORD dwTime)
1125 {
1126     POINT pos;
1127     INT hoverwidth = 0, hoverheight = 0, hittest;
1128
1129     TRACE("hwnd %p, msg %04x, id %04lx, time %u\n", hwnd, uMsg, idEvent, dwTime);
1130
1131     GetCursorPos(&pos);
1132     hwnd = WINPOS_WindowFromPoint(hwnd, pos, &hittest);
1133
1134     TRACE("point %s hwnd %p hittest %d\n", wine_dbgstr_point(&pos), hwnd, hittest);
1135
1136     SystemParametersInfoW(SPI_GETMOUSEHOVERWIDTH, 0, &hoverwidth, 0);
1137     SystemParametersInfoW(SPI_GETMOUSEHOVERHEIGHT, 0, &hoverheight, 0);
1138
1139     TRACE("tracked pos %s, current pos %s, hover width %d, hover height %d\n",
1140            wine_dbgstr_point(&tracking_info.pos), wine_dbgstr_point(&pos),
1141            hoverwidth, hoverheight);
1142
1143     /* see if this tracking event is looking for TME_LEAVE and that the */
1144     /* mouse has left the window */
1145     if (tracking_info.tme.dwFlags & TME_LEAVE)
1146     {
1147         check_mouse_leave(hwnd, hittest);
1148     }
1149
1150     if (tracking_info.tme.hwndTrack != hwnd)
1151     {
1152         /* mouse is gone, stop tracking mouse hover */
1153         tracking_info.tme.dwFlags &= ~TME_HOVER;
1154     }
1155
1156     /* see if we are tracking hovering for this hwnd */
1157     if (tracking_info.tme.dwFlags & TME_HOVER)
1158     {
1159         /* has the cursor moved outside the rectangle centered around pos? */
1160         if ((abs(pos.x - tracking_info.pos.x) > (hoverwidth / 2)) ||
1161             (abs(pos.y - tracking_info.pos.y) > (hoverheight / 2)))
1162         {
1163             /* record this new position as the current position */
1164             tracking_info.pos = pos;
1165         }
1166         else
1167         {
1168             if (hittest == HTCLIENT)
1169             {
1170                 ScreenToClient(hwnd, &pos);
1171                 TRACE("client cursor pos %s\n", wine_dbgstr_point(&pos));
1172
1173                 PostMessageW(tracking_info.tme.hwndTrack, WM_MOUSEHOVER,
1174                              get_key_state(), MAKELPARAM( pos.x, pos.y ));
1175             }
1176             else
1177             {
1178                 if (tracking_info.tme.dwFlags & TME_NONCLIENT)
1179                     PostMessageW(tracking_info.tme.hwndTrack, WM_NCMOUSEHOVER,
1180                                  hittest, MAKELPARAM( pos.x, pos.y ));
1181             }
1182
1183             /* stop tracking mouse hover */
1184             tracking_info.tme.dwFlags &= ~TME_HOVER;
1185         }
1186     }
1187
1188     /* stop the timer if the tracking list is empty */
1189     if (!(tracking_info.tme.dwFlags & (TME_HOVER | TME_LEAVE)))
1190     {
1191         KillSystemTimer(tracking_info.tme.hwndTrack, timer);
1192         timer = 0;
1193         tracking_info.tme.hwndTrack = 0;
1194         tracking_info.tme.dwFlags = 0;
1195         tracking_info.tme.dwHoverTime = 0;
1196     }
1197 }
1198
1199
1200 /***********************************************************************
1201  * TrackMouseEvent [USER32]
1202  *
1203  * Requests notification of mouse events
1204  *
1205  * During mouse tracking WM_MOUSEHOVER or WM_MOUSELEAVE events are posted
1206  * to the hwnd specified in the ptme structure.  After the event message
1207  * is posted to the hwnd, the entry in the queue is removed.
1208  *
1209  * If the current hwnd isn't ptme->hwndTrack the TME_HOVER flag is completely
1210  * ignored. The TME_LEAVE flag results in a WM_MOUSELEAVE message being posted
1211  * immediately and the TME_LEAVE flag being ignored.
1212  *
1213  * PARAMS
1214  *     ptme [I,O] pointer to TRACKMOUSEEVENT information structure.
1215  *
1216  * RETURNS
1217  *     Success: non-zero
1218  *     Failure: zero
1219  *
1220  */
1221
1222 BOOL WINAPI
1223 TrackMouseEvent (TRACKMOUSEEVENT *ptme)
1224 {
1225     HWND hwnd;
1226     POINT pos;
1227     DWORD hover_time;
1228     INT hittest;
1229
1230     TRACE("%x, %x, %p, %u\n", ptme->cbSize, ptme->dwFlags, ptme->hwndTrack, ptme->dwHoverTime);
1231
1232     if (ptme->cbSize != sizeof(TRACKMOUSEEVENT)) {
1233         WARN("wrong TRACKMOUSEEVENT size from app\n");
1234         SetLastError(ERROR_INVALID_PARAMETER);
1235         return FALSE;
1236     }
1237
1238     /* fill the TRACKMOUSEEVENT struct with the current tracking for the given hwnd */
1239     if (ptme->dwFlags & TME_QUERY )
1240     {
1241         *ptme = tracking_info.tme;
1242         /* set cbSize in the case it's not initialized yet */
1243         ptme->cbSize = sizeof(TRACKMOUSEEVENT);
1244
1245         return TRUE; /* return here, TME_QUERY is retrieving information */
1246     }
1247
1248     if (!IsWindow(ptme->hwndTrack))
1249     {
1250         SetLastError(ERROR_INVALID_WINDOW_HANDLE);
1251         return FALSE;
1252     }
1253
1254     hover_time = (ptme->dwFlags & TME_HOVER) ? ptme->dwHoverTime : HOVER_DEFAULT;
1255
1256     /* if HOVER_DEFAULT was specified replace this with the system's current value.
1257      * TME_LEAVE doesn't need to specify hover time so use default */
1258     if (hover_time == HOVER_DEFAULT || hover_time == 0)
1259         SystemParametersInfoW(SPI_GETMOUSEHOVERTIME, 0, &hover_time, 0);
1260
1261     GetCursorPos(&pos);
1262     hwnd = WINPOS_WindowFromPoint(ptme->hwndTrack, pos, &hittest);
1263     TRACE("point %s hwnd %p hittest %d\n", wine_dbgstr_point(&pos), hwnd, hittest);
1264
1265     if (ptme->dwFlags & ~(TME_CANCEL | TME_HOVER | TME_LEAVE | TME_NONCLIENT))
1266         FIXME("Unknown flag(s) %08x\n", ptme->dwFlags & ~(TME_CANCEL | TME_HOVER | TME_LEAVE | TME_NONCLIENT));
1267
1268     if (ptme->dwFlags & TME_CANCEL)
1269     {
1270         if (tracking_info.tme.hwndTrack == ptme->hwndTrack)
1271         {
1272             tracking_info.tme.dwFlags &= ~(ptme->dwFlags & ~TME_CANCEL);
1273
1274             /* if we aren't tracking on hover or leave remove this entry */
1275             if (!(tracking_info.tme.dwFlags & (TME_HOVER | TME_LEAVE)))
1276             {
1277                 KillSystemTimer(tracking_info.tme.hwndTrack, timer);
1278                 timer = 0;
1279                 tracking_info.tme.hwndTrack = 0;
1280                 tracking_info.tme.dwFlags = 0;
1281                 tracking_info.tme.dwHoverTime = 0;
1282             }
1283         }
1284     } else {
1285         /* In our implementation it's possible that another window will receive a
1286          * WM_MOUSEMOVE and call TrackMouseEvent before TrackMouseEventProc is
1287          * called. In such a situation post the WM_MOUSELEAVE now */
1288         if (tracking_info.tme.dwFlags & TME_LEAVE && tracking_info.tme.hwndTrack != NULL)
1289             check_mouse_leave(hwnd, hittest);
1290
1291         if (timer)
1292         {
1293             KillSystemTimer(tracking_info.tme.hwndTrack, timer);
1294             timer = 0;
1295             tracking_info.tme.hwndTrack = 0;
1296             tracking_info.tme.dwFlags = 0;
1297             tracking_info.tme.dwHoverTime = 0;
1298         }
1299
1300         if (ptme->hwndTrack == hwnd)
1301         {
1302             /* Adding new mouse event to the tracking list */
1303             tracking_info.tme = *ptme;
1304             tracking_info.tme.dwHoverTime = hover_time;
1305
1306             /* Initialize HoverInfo variables even if not hover tracking */
1307             tracking_info.pos = pos;
1308
1309             timer = SetSystemTimer(tracking_info.tme.hwndTrack, (UINT_PTR)&tracking_info.tme, hover_time, TrackMouseEventProc);
1310         }
1311     }
1312
1313     return TRUE;
1314 }
1315
1316 /***********************************************************************
1317  * GetMouseMovePointsEx [USER32]
1318  *
1319  * RETURNS
1320  *     Success: count of point set in the buffer
1321  *     Failure: -1
1322  */
1323 int WINAPI GetMouseMovePointsEx(UINT size, LPMOUSEMOVEPOINT ptin, LPMOUSEMOVEPOINT ptout, int count, DWORD res) {
1324
1325     if((size != sizeof(MOUSEMOVEPOINT)) || (count < 0) || (count > 64)) {
1326         SetLastError(ERROR_INVALID_PARAMETER);
1327         return -1;
1328     }
1329
1330     if(!ptin || (!ptout && count)) {
1331         SetLastError(ERROR_NOACCESS);
1332         return -1;
1333     }
1334
1335     FIXME("(%d %p %p %d %d) stub\n", size, ptin, ptout, count, res);
1336
1337     SetLastError(ERROR_POINT_NOT_FOUND);
1338     return -1;
1339 }