user32/tests: Flush events before the key flags test.
[wine] / dlls / dinput / dinput_main.c
1 /*              DirectInput
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998,1999 Lionel Ulmer
5  * Copyright 2000-2002 TransGaming Technologies Inc.
6  * Copyright 2007 Vitaliy Margolen
7  *
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23 /* Status:
24  *
25  * - Tomb Raider 2 Demo:
26  *   Playable using keyboard only.
27  * - WingCommander Prophecy Demo:
28  *   Doesn't get Input Focus.
29  *
30  * - Fallout : works great in X and DGA mode
31  */
32
33 #include "config.h"
34 #include <assert.h>
35 #include <stdarg.h>
36 #include <string.h>
37
38 #define COBJMACROS
39 #define NONAMELESSUNION
40
41 #include "wine/debug.h"
42 #include "wine/unicode.h"
43 #include "windef.h"
44 #include "winbase.h"
45 #include "winuser.h"
46 #include "winerror.h"
47 #include "objbase.h"
48 #include "rpcproxy.h"
49 #include "dinput_private.h"
50 #include "device_private.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(dinput);
53
54 static const IDirectInput7AVtbl ddi7avt;
55 static const IDirectInput7WVtbl ddi7wvt;
56 static const IDirectInput8AVtbl ddi8avt;
57 static const IDirectInput8WVtbl ddi8wvt;
58
59 static inline IDirectInputImpl *impl_from_IDirectInput7A( IDirectInput7A *iface )
60 {
61     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput7A_iface );
62 }
63
64 static inline IDirectInputImpl *impl_from_IDirectInput7W( IDirectInput7W *iface )
65 {
66     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput7W_iface );
67 }
68
69 static inline IDirectInputImpl *impl_from_IDirectInput8A( IDirectInput8A *iface )
70 {
71     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput8A_iface );
72 }
73
74 static inline IDirectInputImpl *impl_from_IDirectInput8W( IDirectInput8W *iface )
75 {
76     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput8W_iface );
77 }
78
79 static inline IDirectInputDeviceImpl *impl_from_IDirectInputDevice8A(IDirectInputDevice8A *iface)
80 {
81     return CONTAINING_RECORD(iface, IDirectInputDeviceImpl, IDirectInputDevice8A_iface);
82 }
83 static inline IDirectInputDeviceImpl *impl_from_IDirectInputDevice8W(IDirectInputDevice8W *iface)
84 {
85     return CONTAINING_RECORD(iface, IDirectInputDeviceImpl, IDirectInputDevice8W_iface);
86 }
87
88 static const struct dinput_device *dinput_devices[] =
89 {
90     &mouse_device,
91     &keyboard_device,
92     &joystick_linuxinput_device,
93     &joystick_linux_device,
94     &joystick_osx_device
95 };
96 #define NB_DINPUT_DEVICES (sizeof(dinput_devices)/sizeof(dinput_devices[0]))
97
98 static HINSTANCE DINPUT_instance = NULL;
99
100 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserv)
101 {
102     switch(reason)
103     {
104       case DLL_PROCESS_ATTACH:
105         DisableThreadLibraryCalls(inst);
106         DINPUT_instance = inst;
107         break;
108       case DLL_PROCESS_DETACH:
109         break;
110     }
111     return TRUE;
112 }
113
114 static BOOL check_hook_thread(void);
115 static CRITICAL_SECTION dinput_hook_crit;
116 static struct list direct_input_list = LIST_INIT( direct_input_list );
117
118 static HRESULT initialize_directinput_instance(IDirectInputImpl *This, DWORD dwVersion);
119 static void uninitialize_directinput_instance(IDirectInputImpl *This);
120
121 static HRESULT create_directinput_instance(REFIID riid, LPVOID *ppDI, IDirectInputImpl **out)
122 {
123     IDirectInputImpl *This = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectInputImpl) );
124     HRESULT hr;
125
126     if (!This)
127         return E_OUTOFMEMORY;
128
129     This->IDirectInput7A_iface.lpVtbl = &ddi7avt;
130     This->IDirectInput7W_iface.lpVtbl = &ddi7wvt;
131     This->IDirectInput8A_iface.lpVtbl = &ddi8avt;
132     This->IDirectInput8W_iface.lpVtbl = &ddi8wvt;
133
134     hr = IDirectInput_QueryInterface( &This->IDirectInput7A_iface, riid, ppDI );
135     if (FAILED(hr))
136     {
137         HeapFree( GetProcessHeap(), 0, This );
138         return hr;
139     }
140
141     if (out) *out = This;
142     return DI_OK;
143 }
144
145 /******************************************************************************
146  *      DirectInputCreateEx (DINPUT.@)
147  */
148 HRESULT WINAPI DirectInputCreateEx(
149         HINSTANCE hinst, DWORD dwVersion, REFIID riid, LPVOID *ppDI,
150         LPUNKNOWN punkOuter)
151 {
152     IDirectInputImpl *This;
153     HRESULT hr;
154
155     TRACE("(%p,%04x,%s,%p,%p)\n", hinst, dwVersion, debugstr_guid(riid), ppDI, punkOuter);
156
157     if (IsEqualGUID( &IID_IDirectInputA,  riid ) ||
158         IsEqualGUID( &IID_IDirectInput2A, riid ) ||
159         IsEqualGUID( &IID_IDirectInput7A, riid ) ||
160         IsEqualGUID( &IID_IDirectInputW,  riid ) ||
161         IsEqualGUID( &IID_IDirectInput2W, riid ) ||
162         IsEqualGUID( &IID_IDirectInput7W, riid ))
163     {
164         hr = create_directinput_instance(riid, ppDI, &This);
165         if (FAILED(hr))
166             return hr;
167     }
168     else
169         return DIERR_NOINTERFACE;
170
171     hr = IDirectInput_Initialize( &This->IDirectInput7A_iface, hinst, dwVersion );
172     if (FAILED(hr))
173     {
174         IDirectInput_Release( &This->IDirectInput7A_iface );
175         *ppDI = NULL;
176         return hr;
177     }
178
179     return DI_OK;
180 }
181
182 /******************************************************************************
183  *      DirectInputCreateA (DINPUT.@)
184  */
185 HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateA(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA *ppDI, LPUNKNOWN punkOuter)
186 {
187     return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7A, (LPVOID *)ppDI, punkOuter);
188 }
189
190 /******************************************************************************
191  *      DirectInputCreateW (DINPUT.@)
192  */
193 HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateW(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTW *ppDI, LPUNKNOWN punkOuter)
194 {
195     return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7W, (LPVOID *)ppDI, punkOuter);
196 }
197
198 static const char *_dump_DIDEVTYPE_value(DWORD dwDevType) {
199     switch (dwDevType) {
200         case 0: return "All devices";
201         case DIDEVTYPE_MOUSE: return "DIDEVTYPE_MOUSE";
202         case DIDEVTYPE_KEYBOARD: return "DIDEVTYPE_KEYBOARD";
203         case DIDEVTYPE_JOYSTICK: return "DIDEVTYPE_JOYSTICK";
204         case DIDEVTYPE_DEVICE: return "DIDEVTYPE_DEVICE";
205         default: return "Unknown";
206     }
207 }
208
209 static void _dump_EnumDevices_dwFlags(DWORD dwFlags) {
210     if (TRACE_ON(dinput)) {
211         unsigned int   i;
212         static const struct {
213             DWORD       mask;
214             const char  *name;
215         } flags[] = {
216 #define FE(x) { x, #x}
217             FE(DIEDFL_ALLDEVICES),
218             FE(DIEDFL_ATTACHEDONLY),
219             FE(DIEDFL_FORCEFEEDBACK),
220             FE(DIEDFL_INCLUDEALIASES),
221             FE(DIEDFL_INCLUDEPHANTOMS)
222 #undef FE
223         };
224         TRACE(" flags: ");
225         if (dwFlags == 0) {
226             TRACE("DIEDFL_ALLDEVICES\n");
227             return;
228         }
229         for (i = 0; i < (sizeof(flags) / sizeof(flags[0])); i++)
230             if (flags[i].mask & dwFlags)
231                 TRACE("%s ",flags[i].name);
232     }
233     TRACE("\n");
234 }
235
236 static void _dump_diactionformatA(LPDIACTIONFORMATA lpdiActionFormat) {
237     unsigned int i;
238
239     FIXME("diaf.dwSize = %d\n", lpdiActionFormat->dwSize);
240     FIXME("diaf.dwActionSize = %d\n", lpdiActionFormat->dwActionSize);
241     FIXME("diaf.dwDataSize = %d\n", lpdiActionFormat->dwDataSize);
242     FIXME("diaf.dwNumActions = %d\n", lpdiActionFormat->dwNumActions);
243     FIXME("diaf.rgoAction = %p\n", lpdiActionFormat->rgoAction);
244     FIXME("diaf.guidActionMap = %s\n", debugstr_guid(&lpdiActionFormat->guidActionMap));
245     FIXME("diaf.dwGenre = 0x%08x\n", lpdiActionFormat->dwGenre);
246     FIXME("diaf.dwBufferSize = %d\n", lpdiActionFormat->dwBufferSize);
247     FIXME("diaf.lAxisMin = %d\n", lpdiActionFormat->lAxisMin);
248     FIXME("diaf.lAxisMax = %d\n", lpdiActionFormat->lAxisMax);
249     FIXME("diaf.hInstString = %p\n", lpdiActionFormat->hInstString);
250     FIXME("diaf.ftTimeStamp ...\n");
251     FIXME("diaf.dwCRC = 0x%x\n", lpdiActionFormat->dwCRC);
252     FIXME("diaf.tszActionMap = %s\n", debugstr_a(lpdiActionFormat->tszActionMap));
253     for (i = 0; i < lpdiActionFormat->dwNumActions; i++)
254     {
255         FIXME("diaf.rgoAction[%u]:\n", i);
256         FIXME("\tuAppData=0x%lx\n", lpdiActionFormat->rgoAction[i].uAppData);
257         FIXME("\tdwSemantic=0x%08x\n", lpdiActionFormat->rgoAction[i].dwSemantic);
258         FIXME("\tdwFlags=0x%x\n", lpdiActionFormat->rgoAction[i].dwFlags);
259         FIXME("\tszActionName=%s\n", debugstr_a(lpdiActionFormat->rgoAction[i].u.lptszActionName));
260         FIXME("\tguidInstance=%s\n", debugstr_guid(&lpdiActionFormat->rgoAction[i].guidInstance));
261         FIXME("\tdwObjID=0x%x\n", lpdiActionFormat->rgoAction[i].dwObjID);
262         FIXME("\tdwHow=0x%x\n", lpdiActionFormat->rgoAction[i].dwHow);
263     }
264 }
265
266 void _copy_diactionformatAtoW(LPDIACTIONFORMATW to, LPDIACTIONFORMATA from)
267 {
268     int i;
269
270     to->dwSize = sizeof(DIACTIONFORMATW);
271     to->dwActionSize = sizeof(DIACTIONW);
272     to->dwDataSize = from->dwDataSize;
273     to->dwNumActions = from->dwNumActions;
274     to->guidActionMap = from->guidActionMap;
275     to->dwGenre = from->dwGenre;
276     to->dwBufferSize = from->dwBufferSize;
277     to->lAxisMin = from->lAxisMin;
278     to->lAxisMax = from->lAxisMax;
279     to->dwCRC = from->dwCRC;
280     to->ftTimeStamp = from->ftTimeStamp;
281
282     for (i=0; i < to->dwNumActions; i++)
283     {
284         to->rgoAction[i].uAppData = from->rgoAction[i].uAppData;
285         to->rgoAction[i].dwSemantic = from->rgoAction[i].dwSemantic;
286         to->rgoAction[i].dwFlags = from->rgoAction[i].dwFlags;
287         to->rgoAction[i].guidInstance = from->rgoAction[i].guidInstance;
288         to->rgoAction[i].dwObjID = from->rgoAction[i].dwObjID;
289         to->rgoAction[i].dwHow = from->rgoAction[i].dwHow;
290     }
291 }
292
293 void _copy_diactionformatWtoA(LPDIACTIONFORMATA to, LPDIACTIONFORMATW from)
294 {
295     int i;
296
297     to->dwSize = sizeof(DIACTIONFORMATA);
298     to->dwActionSize = sizeof(DIACTIONA);
299     to->dwDataSize = from->dwDataSize;
300     to->dwNumActions = from->dwNumActions;
301     to->guidActionMap = from->guidActionMap;
302     to->dwGenre = from->dwGenre;
303     to->dwBufferSize = from->dwBufferSize;
304     to->lAxisMin = from->lAxisMin;
305     to->lAxisMax = from->lAxisMax;
306     to->dwCRC = from->dwCRC;
307     to->ftTimeStamp = from->ftTimeStamp;
308
309     for (i=0; i < to->dwNumActions; i++)
310     {
311         to->rgoAction[i].uAppData = from->rgoAction[i].uAppData;
312         to->rgoAction[i].dwSemantic = from->rgoAction[i].dwSemantic;
313         to->rgoAction[i].dwFlags = from->rgoAction[i].dwFlags;
314         to->rgoAction[i].guidInstance = from->rgoAction[i].guidInstance;
315         to->rgoAction[i].dwObjID = from->rgoAction[i].dwObjID;
316         to->rgoAction[i].dwHow = from->rgoAction[i].dwHow;
317     }
318 }
319
320 /* _diactionformat_priority
321  *
322  *  Given a DIACTIONFORMAT structure and a DI genre, returns the enumeration
323  *  priority. Joysticks should pass the game genre, and mouse or keyboard their
324  *  respective DI*_MASK
325  */
326 static DWORD _diactionformat_priorityA(LPDIACTIONFORMATA lpdiaf, DWORD genre)
327 {
328     int i;
329     DWORD priorityFlags = 0;
330
331     /* If there's at least one action for the device it's priority 1 */
332     for(i=0; i < lpdiaf->dwActionSize; i++)
333         if ((lpdiaf->rgoAction[i].dwSemantic & genre) == genre)
334             priorityFlags |= DIEDBS_MAPPEDPRI1;
335
336     return priorityFlags;
337 }
338
339 static DWORD _diactionformat_priorityW(LPDIACTIONFORMATW lpdiaf, DWORD genre)
340 {
341     int i;
342     DWORD priorityFlags = 0;
343
344     /* If there's at least one action for the device it's priority 1 */
345     for(i=0; i < lpdiaf->dwActionSize; i++)
346         if ((lpdiaf->rgoAction[i].dwSemantic & genre) == genre)
347             priorityFlags |= DIEDBS_MAPPEDPRI1;
348
349     return priorityFlags;
350 }
351
352 /******************************************************************************
353  *      IDirectInputA_EnumDevices
354  */
355 static HRESULT WINAPI IDirectInputAImpl_EnumDevices(
356         LPDIRECTINPUT7A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
357         LPVOID pvRef, DWORD dwFlags)
358 {
359     IDirectInputImpl *This = impl_from_IDirectInput7A(iface);
360     DIDEVICEINSTANCEA devInstance;
361     unsigned int i;
362     int j, r;
363
364     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
365           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
366           lpCallback, pvRef, dwFlags);
367     _dump_EnumDevices_dwFlags(dwFlags);
368
369     if (!lpCallback)
370         return DIERR_INVALIDPARAM;
371
372     if (!This->initialized)
373         return DIERR_NOTINITIALIZED;
374
375     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
376         if (!dinput_devices[i]->enum_deviceA) continue;
377         for (j = 0, r = -1; r != 0; j++) {
378             devInstance.dwSize = sizeof(devInstance);
379             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
380             if ((r = dinput_devices[i]->enum_deviceA(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
381                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
382                     return 0;
383             }
384         }
385     }
386     
387     return 0;
388 }
389 /******************************************************************************
390  *      IDirectInputW_EnumDevices
391  */
392 static HRESULT WINAPI IDirectInputWImpl_EnumDevices(
393         LPDIRECTINPUT7W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
394         LPVOID pvRef, DWORD dwFlags) 
395 {
396     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
397     DIDEVICEINSTANCEW devInstance;
398     unsigned int i;
399     int j, r;
400
401     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
402           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
403           lpCallback, pvRef, dwFlags);
404     _dump_EnumDevices_dwFlags(dwFlags);
405
406     if (!lpCallback)
407         return DIERR_INVALIDPARAM;
408
409     if (!This->initialized)
410         return DIERR_NOTINITIALIZED;
411
412     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
413         if (!dinput_devices[i]->enum_deviceW) continue;
414         for (j = 0, r = -1; r != 0; j++) {
415             devInstance.dwSize = sizeof(devInstance);
416             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
417             if ((r = dinput_devices[i]->enum_deviceW(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
418                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
419                     return 0;
420             }
421         }
422     }
423     
424     return 0;
425 }
426
427 static ULONG WINAPI IDirectInputAImpl_AddRef(LPDIRECTINPUT7A iface)
428 {
429     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
430     ULONG ref = InterlockedIncrement(&This->ref);
431
432     TRACE( "(%p) incrementing from %d\n", This, ref - 1);
433     return ref;
434 }
435
436 static ULONG WINAPI IDirectInputWImpl_AddRef(LPDIRECTINPUT7W iface)
437 {
438     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
439     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
440 }
441
442 static ULONG WINAPI IDirectInputAImpl_Release(LPDIRECTINPUT7A iface)
443 {
444     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
445     ULONG ref = InterlockedDecrement( &This->ref );
446
447     TRACE( "(%p) releasing from %d\n", This, ref + 1 );
448
449     if (ref == 0)
450     {
451         uninitialize_directinput_instance( This );
452         HeapFree( GetProcessHeap(), 0, This );
453     }
454
455     return ref;
456 }
457
458 static ULONG WINAPI IDirectInputWImpl_Release(LPDIRECTINPUT7W iface)
459 {
460     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
461     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
462 }
463
464 static HRESULT WINAPI IDirectInputAImpl_QueryInterface(LPDIRECTINPUT7A iface, REFIID riid, LPVOID *ppobj)
465 {
466     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
467
468     TRACE( "(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppobj );
469
470     if (!riid || !ppobj)
471         return E_POINTER;
472
473     if (IsEqualGUID( &IID_IUnknown, riid ) ||
474         IsEqualGUID( &IID_IDirectInputA,  riid ) ||
475         IsEqualGUID( &IID_IDirectInput2A, riid ) ||
476         IsEqualGUID( &IID_IDirectInput7A, riid ))
477     {
478         *ppobj = &This->IDirectInput7A_iface;
479         IUnknown_AddRef( (IUnknown*)*ppobj );
480
481         return DI_OK;
482     }
483
484     if (IsEqualGUID( &IID_IDirectInputW,  riid ) ||
485         IsEqualGUID( &IID_IDirectInput2W, riid ) ||
486         IsEqualGUID( &IID_IDirectInput7W, riid ))
487     {
488         *ppobj = &This->IDirectInput7W_iface;
489         IUnknown_AddRef( (IUnknown*)*ppobj );
490
491         return DI_OK;
492     }
493
494     if (IsEqualGUID( &IID_IDirectInput8A, riid ))
495     {
496         *ppobj = &This->IDirectInput8A_iface;
497         IUnknown_AddRef( (IUnknown*)*ppobj );
498
499         return DI_OK;
500     }
501
502     if (IsEqualGUID( &IID_IDirectInput8W, riid ))
503     {
504         *ppobj = &This->IDirectInput8W_iface;
505         IUnknown_AddRef( (IUnknown*)*ppobj );
506
507         return DI_OK;
508     }
509
510     FIXME( "Unsupported interface: %s\n", debugstr_guid(riid));
511     *ppobj = NULL;
512     return E_NOINTERFACE;
513 }
514
515 static HRESULT WINAPI IDirectInputWImpl_QueryInterface(LPDIRECTINPUT7W iface, REFIID riid, LPVOID *ppobj)
516 {
517     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
518     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
519 }
520
521 static HRESULT initialize_directinput_instance(IDirectInputImpl *This, DWORD dwVersion)
522 {
523     if (!This->initialized)
524     {
525         This->dwVersion = dwVersion;
526         This->evsequence = 1;
527
528         InitializeCriticalSection( &This->crit );
529         This->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": IDirectInputImpl*->crit");
530
531         list_init( &This->devices_list );
532
533         /* Add self to the list of the IDirectInputs */
534         EnterCriticalSection( &dinput_hook_crit );
535         list_add_head( &direct_input_list, &This->entry );
536         LeaveCriticalSection( &dinput_hook_crit );
537
538         This->initialized = TRUE;
539
540         if (!check_hook_thread())
541         {
542             uninitialize_directinput_instance( This );
543             return DIERR_GENERIC;
544         }
545     }
546
547     return DI_OK;
548 }
549
550 static void uninitialize_directinput_instance(IDirectInputImpl *This)
551 {
552     if (This->initialized)
553     {
554         /* Remove self from the list of the IDirectInputs */
555         EnterCriticalSection( &dinput_hook_crit );
556         list_remove( &This->entry );
557         LeaveCriticalSection( &dinput_hook_crit );
558
559         check_hook_thread();
560
561         This->crit.DebugInfo->Spare[0] = 0;
562         DeleteCriticalSection( &This->crit );
563
564         This->initialized = FALSE;
565     }
566 }
567
568 enum directinput_versions
569 {
570     DIRECTINPUT_VERSION_300 = 0x0300,
571     DIRECTINPUT_VERSION_500 = 0x0500,
572     DIRECTINPUT_VERSION_50A = 0x050A,
573     DIRECTINPUT_VERSION_5B2 = 0x05B2,
574     DIRECTINPUT_VERSION_602 = 0x0602,
575     DIRECTINPUT_VERSION_61A = 0x061A,
576     DIRECTINPUT_VERSION_700 = 0x0700,
577 };
578
579 static HRESULT WINAPI IDirectInputAImpl_Initialize(LPDIRECTINPUT7A iface, HINSTANCE hinst, DWORD version)
580 {
581     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
582
583     TRACE("(%p)->(%p, 0x%04x)\n", iface, hinst, version);
584
585     if (!hinst)
586         return DIERR_INVALIDPARAM;
587     else if (version == 0)
588         return DIERR_NOTINITIALIZED;
589     else if (version > DIRECTINPUT_VERSION_700)
590         return DIERR_OLDDIRECTINPUTVERSION;
591     else if (version != DIRECTINPUT_VERSION_300 && version != DIRECTINPUT_VERSION_500 &&
592              version != DIRECTINPUT_VERSION_50A && version != DIRECTINPUT_VERSION_5B2 &&
593              version != DIRECTINPUT_VERSION_602 && version != DIRECTINPUT_VERSION_61A &&
594              version != DIRECTINPUT_VERSION_700 && version != DIRECTINPUT_VERSION)
595         return DIERR_BETADIRECTINPUTVERSION;
596
597     return initialize_directinput_instance(This, version);
598 }
599
600 static HRESULT WINAPI IDirectInputWImpl_Initialize(LPDIRECTINPUT7W iface, HINSTANCE hinst, DWORD x)
601 {
602     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
603     return IDirectInputAImpl_Initialize( &This->IDirectInput7A_iface, hinst, x );
604 }
605
606 static HRESULT WINAPI IDirectInputAImpl_GetDeviceStatus(LPDIRECTINPUT7A iface, REFGUID rguid)
607 {
608     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
609     HRESULT hr;
610     LPDIRECTINPUTDEVICEA device;
611
612     TRACE( "(%p)->(%s)\n", This, debugstr_guid(rguid) );
613
614     if (!This->initialized)
615         return DIERR_NOTINITIALIZED;
616
617     hr = IDirectInput_CreateDevice( iface, rguid, &device, NULL );
618     if (hr != DI_OK) return DI_NOTATTACHED;
619
620     IUnknown_Release( device );
621
622     return DI_OK;
623 }
624
625 static HRESULT WINAPI IDirectInputWImpl_GetDeviceStatus(LPDIRECTINPUT7W iface, REFGUID rguid)
626 {
627     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
628     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
629 }
630
631 static HRESULT WINAPI IDirectInputAImpl_RunControlPanel(LPDIRECTINPUT7A iface,
632                                                         HWND hwndOwner,
633                                                         DWORD dwFlags)
634 {
635     WCHAR control_exeW[] = {'c','o','n','t','r','o','l','.','e','x','e',0};
636     STARTUPINFOW si = {0};
637     PROCESS_INFORMATION pi;
638
639     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
640
641     TRACE( "(%p)->(%p, %08x)\n", This, hwndOwner, dwFlags );
642
643     if (hwndOwner && !IsWindow(hwndOwner))
644         return E_HANDLE;
645
646     if (dwFlags)
647         return DIERR_INVALIDPARAM;
648
649     if (!This->initialized)
650         return DIERR_NOTINITIALIZED;
651
652     if (!CreateProcessW(NULL, control_exeW, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
653         return HRESULT_FROM_WIN32(GetLastError());
654
655     return DI_OK;
656 }
657
658 static HRESULT WINAPI IDirectInputWImpl_RunControlPanel(LPDIRECTINPUT7W iface, HWND hwndOwner, DWORD dwFlags)
659 {
660     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
661     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
662 }
663
664 static HRESULT WINAPI IDirectInput2AImpl_FindDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
665                                                     LPCSTR pszName, LPGUID pguidInstance)
666 {
667     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
668
669     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), pszName, pguidInstance );
670
671     return DI_OK;
672 }
673
674 static HRESULT WINAPI IDirectInput2WImpl_FindDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
675                                                     LPCWSTR pszName, LPGUID pguidInstance)
676 {
677     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
678
679     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), debugstr_w(pszName), pguidInstance );
680
681     return DI_OK;
682 }
683
684 static HRESULT create_device(IDirectInputImpl *This, REFGUID rguid, REFIID riid, LPVOID *pvOut, BOOL unicode)
685 {
686     unsigned int i;
687
688     if (pvOut)
689         *pvOut = NULL;
690
691     if (!rguid || !pvOut)
692         return E_POINTER;
693
694     if (!This->initialized)
695         return DIERR_NOTINITIALIZED;
696
697     /* Loop on all the devices to see if anyone matches the given GUID */
698     for (i = 0; i < NB_DINPUT_DEVICES; i++)
699     {
700         HRESULT ret;
701
702         if (!dinput_devices[i]->create_device) continue;
703         if ((ret = dinput_devices[i]->create_device(This, rguid, riid, pvOut, unicode)) == DI_OK)
704             return DI_OK;
705     }
706
707     WARN("invalid device GUID %s\n", debugstr_guid(rguid));
708     return DIERR_DEVICENOTREG;
709 }
710
711 static HRESULT WINAPI IDirectInput7AImpl_CreateDeviceEx(LPDIRECTINPUT7A iface, REFGUID rguid,
712                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
713 {
714     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
715
716     TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
717
718     return create_device(This, rguid, riid, pvOut, FALSE);
719 }
720
721 static HRESULT WINAPI IDirectInput7WImpl_CreateDeviceEx(LPDIRECTINPUT7W iface, REFGUID rguid,
722                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
723 {
724     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
725
726     TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
727
728     return create_device(This, rguid, riid, pvOut, TRUE);
729 }
730
731 static HRESULT WINAPI IDirectInputAImpl_CreateDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
732                                                      LPDIRECTINPUTDEVICEA* pdev, LPUNKNOWN punk)
733 {
734     return IDirectInput7AImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
735 }
736
737 static HRESULT WINAPI IDirectInputWImpl_CreateDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
738                                                      LPDIRECTINPUTDEVICEW* pdev, LPUNKNOWN punk)
739 {
740     return IDirectInput7WImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
741 }
742
743 /*******************************************************************************
744  *      DirectInput8
745  */
746
747 static ULONG WINAPI IDirectInput8AImpl_AddRef(LPDIRECTINPUT8A iface)
748 {
749     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
750     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
751 }
752
753 static ULONG WINAPI IDirectInput8WImpl_AddRef(LPDIRECTINPUT8W iface)
754 {
755     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
756     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
757 }
758
759 static HRESULT WINAPI IDirectInput8AImpl_QueryInterface(LPDIRECTINPUT8A iface, REFIID riid, LPVOID *ppobj)
760 {
761     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
762     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
763 }
764
765 static HRESULT WINAPI IDirectInput8WImpl_QueryInterface(LPDIRECTINPUT8W iface, REFIID riid, LPVOID *ppobj)
766 {
767     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
768     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
769 }
770
771 static ULONG WINAPI IDirectInput8AImpl_Release(LPDIRECTINPUT8A iface)
772 {
773     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
774     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
775 }
776
777 static ULONG WINAPI IDirectInput8WImpl_Release(LPDIRECTINPUT8W iface)
778 {
779     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
780     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
781 }
782
783 static HRESULT WINAPI IDirectInput8AImpl_CreateDevice(LPDIRECTINPUT8A iface, REFGUID rguid,
784                                                       LPDIRECTINPUTDEVICE8A* pdev, LPUNKNOWN punk)
785 {
786     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
787     return IDirectInput7AImpl_CreateDeviceEx( &This->IDirectInput7A_iface, rguid, NULL, (LPVOID*)pdev, punk );
788 }
789
790 static HRESULT WINAPI IDirectInput8WImpl_CreateDevice(LPDIRECTINPUT8W iface, REFGUID rguid,
791                                                       LPDIRECTINPUTDEVICE8W* pdev, LPUNKNOWN punk)
792 {
793     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
794     return IDirectInput7WImpl_CreateDeviceEx( &This->IDirectInput7W_iface, rguid, NULL, (LPVOID*)pdev, punk );
795 }
796
797 static HRESULT WINAPI IDirectInput8AImpl_EnumDevices(LPDIRECTINPUT8A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
798                                                      LPVOID pvRef, DWORD dwFlags)
799 {
800     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
801     return IDirectInputAImpl_EnumDevices( &This->IDirectInput7A_iface, dwDevType, lpCallback, pvRef, dwFlags );
802 }
803
804 static HRESULT WINAPI IDirectInput8WImpl_EnumDevices(LPDIRECTINPUT8W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
805                                                      LPVOID pvRef, DWORD dwFlags)
806 {
807     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
808     return IDirectInputWImpl_EnumDevices( &This->IDirectInput7W_iface, dwDevType, lpCallback, pvRef, dwFlags );
809 }
810
811 static HRESULT WINAPI IDirectInput8AImpl_GetDeviceStatus(LPDIRECTINPUT8A iface, REFGUID rguid)
812 {
813     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
814     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
815 }
816
817 static HRESULT WINAPI IDirectInput8WImpl_GetDeviceStatus(LPDIRECTINPUT8W iface, REFGUID rguid)
818 {
819     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
820     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
821 }
822
823 static HRESULT WINAPI IDirectInput8AImpl_RunControlPanel(LPDIRECTINPUT8A iface, HWND hwndOwner, DWORD dwFlags)
824 {
825     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
826     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
827 }
828
829 static HRESULT WINAPI IDirectInput8WImpl_RunControlPanel(LPDIRECTINPUT8W iface, HWND hwndOwner, DWORD dwFlags)
830 {
831     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
832     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
833 }
834
835 static HRESULT WINAPI IDirectInput8AImpl_Initialize(LPDIRECTINPUT8A iface, HINSTANCE hinst, DWORD version)
836 {
837     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
838
839     TRACE("(%p)->(%p, 0x%04x)\n", iface, hinst, version);
840
841     if (!hinst)
842         return DIERR_INVALIDPARAM;
843     else if (version == 0)
844         return DIERR_NOTINITIALIZED;
845     else if (version < DIRECTINPUT_VERSION)
846         return DIERR_BETADIRECTINPUTVERSION;
847     else if (version > DIRECTINPUT_VERSION)
848         return DIERR_OLDDIRECTINPUTVERSION;
849
850     return initialize_directinput_instance(This, version);
851 }
852
853 static HRESULT WINAPI IDirectInput8WImpl_Initialize(LPDIRECTINPUT8W iface, HINSTANCE hinst, DWORD version)
854 {
855     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
856     return IDirectInput8AImpl_Initialize( &This->IDirectInput8A_iface, hinst, version );
857 }
858
859 static HRESULT WINAPI IDirectInput8AImpl_FindDevice(LPDIRECTINPUT8A iface, REFGUID rguid, LPCSTR pszName, LPGUID pguidInstance)
860 {
861     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
862     return IDirectInput2AImpl_FindDevice( &This->IDirectInput7A_iface, rguid, pszName, pguidInstance );
863 }
864
865 static HRESULT WINAPI IDirectInput8WImpl_FindDevice(LPDIRECTINPUT8W iface, REFGUID rguid, LPCWSTR pszName, LPGUID pguidInstance)
866 {
867     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
868     return IDirectInput2WImpl_FindDevice( &This->IDirectInput7W_iface, rguid, pszName, pguidInstance );
869 }
870
871 static HRESULT WINAPI IDirectInput8AImpl_EnumDevicesBySemantics(
872       LPDIRECTINPUT8A iface, LPCSTR ptszUserName, LPDIACTIONFORMATA lpdiActionFormat,
873       LPDIENUMDEVICESBYSEMANTICSCBA lpCallback,
874       LPVOID pvRef, DWORD dwFlags
875 )
876 {
877     static REFGUID guids[2] = { &GUID_SysKeyboard, &GUID_SysMouse };
878     static const DWORD actionMasks[] = { DIKEYBOARD_MASK, DIMOUSE_MASK };
879     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
880     DIDEVICEINSTANCEA didevi;
881     LPDIRECTINPUTDEVICE8A lpdid;
882     DWORD callbackFlags;
883     int i, j;
884
885
886     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, debugstr_a(ptszUserName), lpdiActionFormat,
887           lpCallback, pvRef, dwFlags);
888 #define X(x) if (dwFlags & x) FIXME("\tdwFlags |= "#x"\n");
889         X(DIEDBSFL_ATTACHEDONLY)
890         X(DIEDBSFL_THISUSER)
891         X(DIEDBSFL_FORCEFEEDBACK)
892         X(DIEDBSFL_AVAILABLEDEVICES)
893         X(DIEDBSFL_MULTIMICEKEYBOARDS)
894         X(DIEDBSFL_NONGAMINGDEVICES)
895 #undef X
896
897     _dump_diactionformatA(lpdiActionFormat);
898
899     didevi.dwSize = sizeof(didevi);
900
901     /* Enumerate all the joysticks */
902     for (i = 0; i < NB_DINPUT_DEVICES; i++)
903     {
904         BOOL enumSuccess;
905
906         if (!dinput_devices[i]->enum_deviceA) continue;
907
908         for (j = 0, enumSuccess = -1; enumSuccess != 0; j++)
909         {
910             TRACE(" - checking device %u ('%s')\n", i, dinput_devices[i]->name);
911
912             callbackFlags = _diactionformat_priorityA(lpdiActionFormat, lpdiActionFormat->dwGenre);
913             /* Default behavior is to enumerate attached game controllers */
914             enumSuccess = dinput_devices[i]->enum_deviceA(DI8DEVCLASS_GAMECTRL, DIEDFL_ATTACHEDONLY | dwFlags, &didevi, This->dwVersion, j);
915             if (enumSuccess)
916             {
917                 IDirectInput_CreateDevice(iface, &didevi.guidInstance, &lpdid, NULL);
918
919                 if (lpCallback(&didevi, lpdid, callbackFlags, 0, pvRef) == DIENUM_STOP)
920                     return DI_OK;
921             }
922         }
923     }
924
925     if (dwFlags & DIEDBSFL_FORCEFEEDBACK) return DI_OK;
926
927     /* Enumerate keyboard and mouse */
928     for(i=0; i < sizeof(guids)/sizeof(guids[0]); i++)
929     {
930         callbackFlags = _diactionformat_priorityA(lpdiActionFormat, actionMasks[i]);
931
932         IDirectInput_CreateDevice(iface, guids[i], &lpdid, NULL);
933         IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
934
935         if (lpCallback(&didevi, lpdid, callbackFlags, sizeof(guids)/sizeof(guids[0]) - (i+1), pvRef) == DIENUM_STOP)
936             return DI_OK;
937     }
938
939     return DI_OK;
940 }
941
942 static HRESULT WINAPI IDirectInput8WImpl_EnumDevicesBySemantics(
943       LPDIRECTINPUT8W iface, LPCWSTR ptszUserName, LPDIACTIONFORMATW lpdiActionFormat,
944       LPDIENUMDEVICESBYSEMANTICSCBW lpCallback,
945       LPVOID pvRef, DWORD dwFlags
946 )
947 {
948     static REFGUID guids[2] = { &GUID_SysKeyboard, &GUID_SysMouse };
949     static const DWORD actionMasks[] = { DIKEYBOARD_MASK, DIMOUSE_MASK };
950     IDirectInputImpl *This = impl_from_IDirectInput8W(iface);
951     DIDEVICEINSTANCEW didevi;
952     LPDIRECTINPUTDEVICE8W lpdid;
953     DWORD callbackFlags;
954     int i, j;
955
956     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, debugstr_w(ptszUserName), lpdiActionFormat,
957           lpCallback, pvRef, dwFlags);
958
959     didevi.dwSize = sizeof(didevi);
960
961     /* Enumerate all the joysticks */
962     for (i = 0; i < NB_DINPUT_DEVICES; i++)
963     {
964         BOOL enumSuccess;
965
966         if (!dinput_devices[i]->enum_deviceW) continue;
967
968         for (j = 0, enumSuccess = -1; enumSuccess != 0; j++)
969         {
970             TRACE(" - checking device %u ('%s')\n", i, dinput_devices[i]->name);
971
972             callbackFlags = _diactionformat_priorityW(lpdiActionFormat, lpdiActionFormat->dwGenre);
973             /* Default behavior is to enumerate attached game controllers */
974             enumSuccess = dinput_devices[i]->enum_deviceW(DI8DEVCLASS_GAMECTRL, DIEDFL_ATTACHEDONLY | dwFlags, &didevi, This->dwVersion, j);
975             if (enumSuccess)
976             {
977                 IDirectInput_CreateDevice(iface, &didevi.guidInstance, &lpdid, NULL);
978
979                 if (lpCallback(&didevi, lpdid, callbackFlags, 0, pvRef) == DIENUM_STOP)
980                     return DI_OK;
981             }
982         }
983     }
984
985     if (dwFlags & DIEDBSFL_FORCEFEEDBACK) return DI_OK;
986
987     /* Enumerate keyboard and mouse */
988     for(i=0; i < sizeof(guids)/sizeof(guids[0]); i++)
989     {
990         callbackFlags = _diactionformat_priorityW(lpdiActionFormat, actionMasks[i]);
991
992         IDirectInput_CreateDevice(iface, guids[i], &lpdid, NULL);
993         IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
994
995         if (lpCallback(&didevi, lpdid, callbackFlags, sizeof(guids)/sizeof(guids[0]) - (i+1), pvRef) == DIENUM_STOP)
996             return DI_OK;
997     }
998
999     return DI_OK;
1000 }
1001
1002 static HRESULT WINAPI IDirectInput8WImpl_ConfigureDevices(
1003       LPDIRECTINPUT8W iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
1004       LPDICONFIGUREDEVICESPARAMSW lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
1005 )
1006 {
1007     IDirectInputImpl *This = impl_from_IDirectInput8W(iface);
1008
1009     FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams, dwFlags, pvRefData);
1010
1011     /* Call helper function in config.c to do the real work */
1012     return _configure_devices(iface, lpdiCallback, lpdiCDParams, dwFlags, pvRefData);
1013 }
1014
1015 static HRESULT WINAPI IDirectInput8AImpl_ConfigureDevices(
1016       LPDIRECTINPUT8A iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
1017       LPDICONFIGUREDEVICESPARAMSA lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
1018 )
1019 {
1020     IDirectInputImpl *This = impl_from_IDirectInput8A(iface);
1021     DIACTIONFORMATW diafW;
1022     DICONFIGUREDEVICESPARAMSW diCDParamsW;
1023     HRESULT hr;
1024     int i;
1025
1026      FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams, dwFlags, pvRefData);
1027
1028     /* Copy parameters */
1029     diCDParamsW.dwSize = sizeof(DICONFIGUREDEVICESPARAMSW);
1030     diCDParamsW.dwcFormats = lpdiCDParams->dwcFormats;
1031     diCDParamsW.lprgFormats = &diafW;
1032     diCDParamsW.hwnd = lpdiCDParams->hwnd;
1033
1034     diafW.rgoAction = HeapAlloc(GetProcessHeap(), 0, sizeof(DIACTIONW)*lpdiCDParams->lprgFormats->dwNumActions);
1035     _copy_diactionformatAtoW(&diafW, lpdiCDParams->lprgFormats);
1036
1037     /* Copy action names */
1038     for (i=0; i < diafW.dwNumActions; i++)
1039     {
1040         const char* from = lpdiCDParams->lprgFormats->rgoAction[i].u.lptszActionName;
1041         int len = MultiByteToWideChar(CP_ACP, 0, from , -1, NULL , 0);
1042         WCHAR *to = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR)*len);
1043
1044         MultiByteToWideChar(CP_ACP, 0, from , -1, to , len);
1045         diafW.rgoAction[i].u.lptszActionName = to;
1046     }
1047
1048     hr = IDirectInput8WImpl_ConfigureDevices(&This->IDirectInput8W_iface, lpdiCallback, &diCDParamsW, dwFlags, pvRefData);
1049
1050     /* Copy back configuration */
1051     if (SUCCEEDED(hr))
1052         _copy_diactionformatWtoA(lpdiCDParams->lprgFormats, &diafW);
1053
1054     /* Free memory */
1055     for (i=0; i < diafW.dwNumActions; i++)
1056         HeapFree(GetProcessHeap(), 0, (void*) diafW.rgoAction[i].u.lptszActionName);
1057
1058     HeapFree(GetProcessHeap(), 0, diafW.rgoAction);
1059
1060     return hr;
1061 }
1062
1063 static const IDirectInput7AVtbl ddi7avt = {
1064     IDirectInputAImpl_QueryInterface,
1065     IDirectInputAImpl_AddRef,
1066     IDirectInputAImpl_Release,
1067     IDirectInputAImpl_CreateDevice,
1068     IDirectInputAImpl_EnumDevices,
1069     IDirectInputAImpl_GetDeviceStatus,
1070     IDirectInputAImpl_RunControlPanel,
1071     IDirectInputAImpl_Initialize,
1072     IDirectInput2AImpl_FindDevice,
1073     IDirectInput7AImpl_CreateDeviceEx
1074 };
1075
1076 static const IDirectInput7WVtbl ddi7wvt = {
1077     IDirectInputWImpl_QueryInterface,
1078     IDirectInputWImpl_AddRef,
1079     IDirectInputWImpl_Release,
1080     IDirectInputWImpl_CreateDevice,
1081     IDirectInputWImpl_EnumDevices,
1082     IDirectInputWImpl_GetDeviceStatus,
1083     IDirectInputWImpl_RunControlPanel,
1084     IDirectInputWImpl_Initialize,
1085     IDirectInput2WImpl_FindDevice,
1086     IDirectInput7WImpl_CreateDeviceEx
1087 };
1088
1089 static const IDirectInput8AVtbl ddi8avt = {
1090     IDirectInput8AImpl_QueryInterface,
1091     IDirectInput8AImpl_AddRef,
1092     IDirectInput8AImpl_Release,
1093     IDirectInput8AImpl_CreateDevice,
1094     IDirectInput8AImpl_EnumDevices,
1095     IDirectInput8AImpl_GetDeviceStatus,
1096     IDirectInput8AImpl_RunControlPanel,
1097     IDirectInput8AImpl_Initialize,
1098     IDirectInput8AImpl_FindDevice,
1099     IDirectInput8AImpl_EnumDevicesBySemantics,
1100     IDirectInput8AImpl_ConfigureDevices
1101 };
1102
1103 static const IDirectInput8WVtbl ddi8wvt = {
1104     IDirectInput8WImpl_QueryInterface,
1105     IDirectInput8WImpl_AddRef,
1106     IDirectInput8WImpl_Release,
1107     IDirectInput8WImpl_CreateDevice,
1108     IDirectInput8WImpl_EnumDevices,
1109     IDirectInput8WImpl_GetDeviceStatus,
1110     IDirectInput8WImpl_RunControlPanel,
1111     IDirectInput8WImpl_Initialize,
1112     IDirectInput8WImpl_FindDevice,
1113     IDirectInput8WImpl_EnumDevicesBySemantics,
1114     IDirectInput8WImpl_ConfigureDevices
1115 };
1116
1117 /*******************************************************************************
1118  * DirectInput ClassFactory
1119  */
1120 typedef struct
1121 {
1122     /* IUnknown fields */
1123     IClassFactory IClassFactory_iface;
1124     LONG          ref;
1125 } IClassFactoryImpl;
1126
1127 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
1128 {
1129         return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
1130 }
1131
1132 static HRESULT WINAPI DICF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
1133         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1134
1135         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
1136         return E_NOINTERFACE;
1137 }
1138
1139 static ULONG WINAPI DICF_AddRef(LPCLASSFACTORY iface) {
1140         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1141         return InterlockedIncrement(&(This->ref));
1142 }
1143
1144 static ULONG WINAPI DICF_Release(LPCLASSFACTORY iface) {
1145         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1146         /* static class, won't be  freed */
1147         return InterlockedDecrement(&(This->ref));
1148 }
1149
1150 static HRESULT WINAPI DICF_CreateInstance(
1151         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
1152 ) {
1153         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1154
1155         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
1156         if ( IsEqualGUID( &IID_IUnknown, riid ) ||
1157              IsEqualGUID( &IID_IDirectInputA, riid ) ||
1158              IsEqualGUID( &IID_IDirectInputW, riid ) ||
1159              IsEqualGUID( &IID_IDirectInput2A, riid ) ||
1160              IsEqualGUID( &IID_IDirectInput2W, riid ) ||
1161              IsEqualGUID( &IID_IDirectInput7A, riid ) ||
1162              IsEqualGUID( &IID_IDirectInput7W, riid ) ) {
1163                 return create_directinput_instance(riid, ppobj, NULL);
1164         }
1165
1166         FIXME("(%p,%p,%s,%p) Interface not found!\n",This,pOuter,debugstr_guid(riid),ppobj);    
1167         return E_NOINTERFACE;
1168 }
1169
1170 static HRESULT WINAPI DICF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
1171         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1172         FIXME("(%p)->(%d),stub!\n",This,dolock);
1173         return S_OK;
1174 }
1175
1176 static const IClassFactoryVtbl DICF_Vtbl = {
1177         DICF_QueryInterface,
1178         DICF_AddRef,
1179         DICF_Release,
1180         DICF_CreateInstance,
1181         DICF_LockServer
1182 };
1183 static IClassFactoryImpl DINPUT_CF = {{&DICF_Vtbl}, 1 };
1184
1185 /***********************************************************************
1186  *              DllCanUnloadNow (DINPUT.@)
1187  */
1188 HRESULT WINAPI DllCanUnloadNow(void)
1189 {
1190     return S_FALSE;
1191 }
1192
1193 /***********************************************************************
1194  *              DllGetClassObject (DINPUT.@)
1195  */
1196 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
1197 {
1198     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1199     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
1200         *ppv = &DINPUT_CF;
1201         IClassFactory_AddRef((IClassFactory*)*ppv);
1202     return S_OK;
1203     }
1204
1205     FIXME("(%s,%s,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1206     return CLASS_E_CLASSNOTAVAILABLE;
1207 }
1208
1209 /***********************************************************************
1210  *              DllRegisterServer (DINPUT.@)
1211  */
1212 HRESULT WINAPI DllRegisterServer(void)
1213 {
1214     return __wine_register_resources( DINPUT_instance );
1215 }
1216
1217 /***********************************************************************
1218  *              DllUnregisterServer (DINPUT.@)
1219  */
1220 HRESULT WINAPI DllUnregisterServer(void)
1221 {
1222     return __wine_unregister_resources( DINPUT_instance );
1223 }
1224
1225 /******************************************************************************
1226  *      DInput hook thread
1227  */
1228
1229 static LRESULT CALLBACK LL_hook_proc( int code, WPARAM wparam, LPARAM lparam )
1230 {
1231     IDirectInputImpl *dinput;
1232     int skip = 0;
1233
1234     if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );
1235
1236     EnterCriticalSection( &dinput_hook_crit );
1237     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1238     {
1239         IDirectInputDeviceImpl *dev;
1240
1241         EnterCriticalSection( &dinput->crit );
1242         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1243             if (dev->acquired && dev->event_proc)
1244             {
1245                 TRACE("calling %p->%p (%lx %lx)\n", dev, dev->event_proc, wparam, lparam);
1246                 skip |= dev->event_proc( &dev->IDirectInputDevice8A_iface, wparam, lparam );
1247             }
1248         LeaveCriticalSection( &dinput->crit );
1249     }
1250     LeaveCriticalSection( &dinput_hook_crit );
1251
1252     return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
1253 }
1254
1255 static LRESULT CALLBACK callwndproc_proc( int code, WPARAM wparam, LPARAM lparam )
1256 {
1257     CWPSTRUCT *msg = (CWPSTRUCT *)lparam;
1258     IDirectInputImpl *dinput;
1259     HWND foreground;
1260
1261     if (code != HC_ACTION || (msg->message != WM_KILLFOCUS &&
1262         msg->message != WM_ACTIVATEAPP && msg->message != WM_ACTIVATE))
1263         return CallNextHookEx( 0, code, wparam, lparam );
1264
1265     foreground = GetForegroundWindow();
1266
1267     EnterCriticalSection( &dinput_hook_crit );
1268
1269     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1270     {
1271         IDirectInputDeviceImpl *dev;
1272
1273         EnterCriticalSection( &dinput->crit );
1274         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1275         {
1276             if (!dev->acquired) continue;
1277
1278             if (msg->hwnd == dev->win && msg->hwnd != foreground)
1279             {
1280                 TRACE( "%p window is not foreground - unacquiring %p\n", dev->win, dev );
1281                 IDirectInputDevice_Unacquire( &dev->IDirectInputDevice8A_iface );
1282             }
1283         }
1284         LeaveCriticalSection( &dinput->crit );
1285     }
1286     LeaveCriticalSection( &dinput_hook_crit );
1287
1288     return CallNextHookEx( 0, code, wparam, lparam );
1289 }
1290
1291 static DWORD WINAPI hook_thread_proc(void *param)
1292 {
1293     static HHOOK kbd_hook, mouse_hook;
1294     MSG msg;
1295
1296     /* Force creation of the message queue */
1297     PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE );
1298     SetEvent(*(LPHANDLE)param);
1299
1300     while (GetMessageW( &msg, 0, 0, 0 ))
1301     {
1302         UINT kbd_cnt = 0, mice_cnt = 0;
1303
1304         if (msg.message == WM_USER+0x10)
1305         {
1306             IDirectInputImpl *dinput;
1307
1308             TRACE( "Processing hook change notification lp:%ld\n", msg.lParam );
1309
1310             if (!msg.wParam && !msg.lParam)
1311             {
1312                 if (kbd_hook) UnhookWindowsHookEx( kbd_hook );
1313                 if (mouse_hook) UnhookWindowsHookEx( mouse_hook );
1314                 kbd_hook = mouse_hook = NULL;
1315                 break;
1316             }
1317
1318             EnterCriticalSection( &dinput_hook_crit );
1319
1320             /* Count acquired keyboards and mice*/
1321             LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1322             {
1323                 IDirectInputDeviceImpl *dev;
1324
1325                 EnterCriticalSection( &dinput->crit );
1326                 LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1327                 {
1328                     if (!dev->acquired || !dev->event_proc) continue;
1329
1330                     if (IsEqualGUID( &dev->guid, &GUID_SysKeyboard ) ||
1331                         IsEqualGUID( &dev->guid, &DInput_Wine_Keyboard_GUID ))
1332                         kbd_cnt++;
1333                     else
1334                         if (IsEqualGUID( &dev->guid, &GUID_SysMouse ) ||
1335                             IsEqualGUID( &dev->guid, &DInput_Wine_Mouse_GUID ))
1336                             mice_cnt++;
1337                 }
1338                 LeaveCriticalSection( &dinput->crit );
1339             }
1340             LeaveCriticalSection( &dinput_hook_crit );
1341
1342             if (kbd_cnt && !kbd_hook)
1343                 kbd_hook = SetWindowsHookExW( WH_KEYBOARD_LL, LL_hook_proc, DINPUT_instance, 0 );
1344             else if (!kbd_cnt && kbd_hook)
1345             {
1346                 UnhookWindowsHookEx( kbd_hook );
1347                 kbd_hook = NULL;
1348             }
1349
1350             if (mice_cnt && !mouse_hook)
1351                 mouse_hook = SetWindowsHookExW( WH_MOUSE_LL, LL_hook_proc, DINPUT_instance, 0 );
1352             else if (!mice_cnt && mouse_hook)
1353             {
1354                 UnhookWindowsHookEx( mouse_hook );
1355                 mouse_hook = NULL;
1356             }
1357         }
1358         TranslateMessage(&msg);
1359         DispatchMessageW(&msg);
1360     }
1361
1362     return 0;
1363 }
1364
1365 static DWORD hook_thread_id;
1366
1367 static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
1368 {
1369     0, 0, &dinput_hook_crit,
1370     { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
1371       0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
1372 };
1373 static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };
1374
1375 static BOOL check_hook_thread(void)
1376 {
1377     static HANDLE hook_thread;
1378
1379     EnterCriticalSection(&dinput_hook_crit);
1380
1381     TRACE("IDirectInputs left: %d\n", list_count(&direct_input_list));
1382     if (!list_empty(&direct_input_list) && !hook_thread)
1383     {
1384         HANDLE event;
1385
1386         event = CreateEventW(NULL, FALSE, FALSE, NULL);
1387         hook_thread = CreateThread(NULL, 0, hook_thread_proc, &event, 0, &hook_thread_id);
1388         if (event && hook_thread)
1389         {
1390             HANDLE handles[2];
1391             handles[0] = event;
1392             handles[1] = hook_thread;
1393             WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1394         }
1395         LeaveCriticalSection(&dinput_hook_crit);
1396         CloseHandle(event);
1397     }
1398     else if (list_empty(&direct_input_list) && hook_thread)
1399     {
1400         DWORD tid = hook_thread_id;
1401
1402         hook_thread_id = 0;
1403         PostThreadMessageW(tid, WM_USER+0x10, 0, 0);
1404         LeaveCriticalSection(&dinput_hook_crit);
1405
1406         /* wait for hook thread to exit */
1407         WaitForSingleObject(hook_thread, INFINITE);
1408         CloseHandle(hook_thread);
1409         hook_thread = NULL;
1410     }
1411     else
1412         LeaveCriticalSection(&dinput_hook_crit);
1413
1414     return hook_thread_id != 0;
1415 }
1416
1417 void check_dinput_hooks(LPDIRECTINPUTDEVICE8W iface)
1418 {
1419     static HHOOK callwndproc_hook;
1420     static ULONG foreground_cnt;
1421     IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8W(iface);
1422
1423     EnterCriticalSection(&dinput_hook_crit);
1424
1425     if (dev->dwCoopLevel & DISCL_FOREGROUND)
1426     {
1427         if (dev->acquired)
1428             foreground_cnt++;
1429         else
1430             foreground_cnt--;
1431     }
1432
1433     if (foreground_cnt && !callwndproc_hook)
1434         callwndproc_hook = SetWindowsHookExW( WH_CALLWNDPROC, callwndproc_proc,
1435                                               DINPUT_instance, GetCurrentThreadId() );
1436     else if (!foreground_cnt && callwndproc_hook)
1437     {
1438         UnhookWindowsHookEx( callwndproc_hook );
1439         callwndproc_hook = NULL;
1440     }
1441
1442     PostThreadMessageW( hook_thread_id, WM_USER+0x10, 1, 0 );
1443
1444     LeaveCriticalSection(&dinput_hook_crit);
1445 }