dinput: Make _dump_diactionformatA() static.
[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, 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 IDirectInput8AImpl_ConfigureDevices(
1003       LPDIRECTINPUT8A iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
1004       LPDICONFIGUREDEVICESPARAMSA lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
1005 )
1006 {
1007       IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
1008
1009       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
1010             dwFlags, pvRefData);
1011       return 0;
1012 }
1013
1014 static HRESULT WINAPI IDirectInput8WImpl_ConfigureDevices(
1015       LPDIRECTINPUT8W iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
1016       LPDICONFIGUREDEVICESPARAMSW lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
1017 )
1018 {
1019       IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
1020
1021       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
1022             dwFlags, pvRefData);
1023       return 0;
1024 }
1025
1026 static const IDirectInput7AVtbl ddi7avt = {
1027     IDirectInputAImpl_QueryInterface,
1028     IDirectInputAImpl_AddRef,
1029     IDirectInputAImpl_Release,
1030     IDirectInputAImpl_CreateDevice,
1031     IDirectInputAImpl_EnumDevices,
1032     IDirectInputAImpl_GetDeviceStatus,
1033     IDirectInputAImpl_RunControlPanel,
1034     IDirectInputAImpl_Initialize,
1035     IDirectInput2AImpl_FindDevice,
1036     IDirectInput7AImpl_CreateDeviceEx
1037 };
1038
1039 static const IDirectInput7WVtbl ddi7wvt = {
1040     IDirectInputWImpl_QueryInterface,
1041     IDirectInputWImpl_AddRef,
1042     IDirectInputWImpl_Release,
1043     IDirectInputWImpl_CreateDevice,
1044     IDirectInputWImpl_EnumDevices,
1045     IDirectInputWImpl_GetDeviceStatus,
1046     IDirectInputWImpl_RunControlPanel,
1047     IDirectInputWImpl_Initialize,
1048     IDirectInput2WImpl_FindDevice,
1049     IDirectInput7WImpl_CreateDeviceEx
1050 };
1051
1052 static const IDirectInput8AVtbl ddi8avt = {
1053     IDirectInput8AImpl_QueryInterface,
1054     IDirectInput8AImpl_AddRef,
1055     IDirectInput8AImpl_Release,
1056     IDirectInput8AImpl_CreateDevice,
1057     IDirectInput8AImpl_EnumDevices,
1058     IDirectInput8AImpl_GetDeviceStatus,
1059     IDirectInput8AImpl_RunControlPanel,
1060     IDirectInput8AImpl_Initialize,
1061     IDirectInput8AImpl_FindDevice,
1062     IDirectInput8AImpl_EnumDevicesBySemantics,
1063     IDirectInput8AImpl_ConfigureDevices
1064 };
1065
1066 static const IDirectInput8WVtbl ddi8wvt = {
1067     IDirectInput8WImpl_QueryInterface,
1068     IDirectInput8WImpl_AddRef,
1069     IDirectInput8WImpl_Release,
1070     IDirectInput8WImpl_CreateDevice,
1071     IDirectInput8WImpl_EnumDevices,
1072     IDirectInput8WImpl_GetDeviceStatus,
1073     IDirectInput8WImpl_RunControlPanel,
1074     IDirectInput8WImpl_Initialize,
1075     IDirectInput8WImpl_FindDevice,
1076     IDirectInput8WImpl_EnumDevicesBySemantics,
1077     IDirectInput8WImpl_ConfigureDevices
1078 };
1079
1080 /*******************************************************************************
1081  * DirectInput ClassFactory
1082  */
1083 typedef struct
1084 {
1085     /* IUnknown fields */
1086     IClassFactory IClassFactory_iface;
1087     LONG          ref;
1088 } IClassFactoryImpl;
1089
1090 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
1091 {
1092         return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
1093 }
1094
1095 static HRESULT WINAPI DICF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
1096         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1097
1098         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
1099         return E_NOINTERFACE;
1100 }
1101
1102 static ULONG WINAPI DICF_AddRef(LPCLASSFACTORY iface) {
1103         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1104         return InterlockedIncrement(&(This->ref));
1105 }
1106
1107 static ULONG WINAPI DICF_Release(LPCLASSFACTORY iface) {
1108         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1109         /* static class, won't be  freed */
1110         return InterlockedDecrement(&(This->ref));
1111 }
1112
1113 static HRESULT WINAPI DICF_CreateInstance(
1114         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
1115 ) {
1116         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1117
1118         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
1119         if ( IsEqualGUID( &IID_IUnknown, riid ) ||
1120              IsEqualGUID( &IID_IDirectInputA, riid ) ||
1121              IsEqualGUID( &IID_IDirectInputW, riid ) ||
1122              IsEqualGUID( &IID_IDirectInput2A, riid ) ||
1123              IsEqualGUID( &IID_IDirectInput2W, riid ) ||
1124              IsEqualGUID( &IID_IDirectInput7A, riid ) ||
1125              IsEqualGUID( &IID_IDirectInput7W, riid ) ) {
1126                 return create_directinput_instance(riid, ppobj, NULL);
1127         }
1128
1129         FIXME("(%p,%p,%s,%p) Interface not found!\n",This,pOuter,debugstr_guid(riid),ppobj);    
1130         return E_NOINTERFACE;
1131 }
1132
1133 static HRESULT WINAPI DICF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
1134         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1135         FIXME("(%p)->(%d),stub!\n",This,dolock);
1136         return S_OK;
1137 }
1138
1139 static const IClassFactoryVtbl DICF_Vtbl = {
1140         DICF_QueryInterface,
1141         DICF_AddRef,
1142         DICF_Release,
1143         DICF_CreateInstance,
1144         DICF_LockServer
1145 };
1146 static IClassFactoryImpl DINPUT_CF = {{&DICF_Vtbl}, 1 };
1147
1148 /***********************************************************************
1149  *              DllCanUnloadNow (DINPUT.@)
1150  */
1151 HRESULT WINAPI DllCanUnloadNow(void)
1152 {
1153     return S_FALSE;
1154 }
1155
1156 /***********************************************************************
1157  *              DllGetClassObject (DINPUT.@)
1158  */
1159 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
1160 {
1161     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1162     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
1163         *ppv = &DINPUT_CF;
1164         IClassFactory_AddRef((IClassFactory*)*ppv);
1165     return S_OK;
1166     }
1167
1168     FIXME("(%s,%s,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1169     return CLASS_E_CLASSNOTAVAILABLE;
1170 }
1171
1172 /***********************************************************************
1173  *              DllRegisterServer (DINPUT.@)
1174  */
1175 HRESULT WINAPI DllRegisterServer(void)
1176 {
1177     return __wine_register_resources( DINPUT_instance );
1178 }
1179
1180 /***********************************************************************
1181  *              DllUnregisterServer (DINPUT.@)
1182  */
1183 HRESULT WINAPI DllUnregisterServer(void)
1184 {
1185     return __wine_unregister_resources( DINPUT_instance );
1186 }
1187
1188 /******************************************************************************
1189  *      DInput hook thread
1190  */
1191
1192 static LRESULT CALLBACK LL_hook_proc( int code, WPARAM wparam, LPARAM lparam )
1193 {
1194     IDirectInputImpl *dinput;
1195     int skip = 0;
1196
1197     if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );
1198
1199     EnterCriticalSection( &dinput_hook_crit );
1200     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1201     {
1202         IDirectInputDeviceImpl *dev;
1203
1204         EnterCriticalSection( &dinput->crit );
1205         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1206             if (dev->acquired && dev->event_proc)
1207             {
1208                 TRACE("calling %p->%p (%lx %lx)\n", dev, dev->event_proc, wparam, lparam);
1209                 skip |= dev->event_proc( &dev->IDirectInputDevice8A_iface, wparam, lparam );
1210             }
1211         LeaveCriticalSection( &dinput->crit );
1212     }
1213     LeaveCriticalSection( &dinput_hook_crit );
1214
1215     return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
1216 }
1217
1218 static LRESULT CALLBACK callwndproc_proc( int code, WPARAM wparam, LPARAM lparam )
1219 {
1220     CWPSTRUCT *msg = (CWPSTRUCT *)lparam;
1221     IDirectInputImpl *dinput;
1222     HWND foreground;
1223
1224     if (code != HC_ACTION || (msg->message != WM_KILLFOCUS &&
1225         msg->message != WM_ACTIVATEAPP && msg->message != WM_ACTIVATE))
1226         return CallNextHookEx( 0, code, wparam, lparam );
1227
1228     foreground = GetForegroundWindow();
1229
1230     EnterCriticalSection( &dinput_hook_crit );
1231
1232     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1233     {
1234         IDirectInputDeviceImpl *dev;
1235
1236         EnterCriticalSection( &dinput->crit );
1237         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1238         {
1239             if (!dev->acquired) continue;
1240
1241             if (msg->hwnd == dev->win && msg->hwnd != foreground)
1242             {
1243                 TRACE( "%p window is not foreground - unacquiring %p\n", dev->win, dev );
1244                 IDirectInputDevice_Unacquire( &dev->IDirectInputDevice8A_iface );
1245             }
1246         }
1247         LeaveCriticalSection( &dinput->crit );
1248     }
1249     LeaveCriticalSection( &dinput_hook_crit );
1250
1251     return CallNextHookEx( 0, code, wparam, lparam );
1252 }
1253
1254 static DWORD WINAPI hook_thread_proc(void *param)
1255 {
1256     static HHOOK kbd_hook, mouse_hook;
1257     MSG msg;
1258
1259     /* Force creation of the message queue */
1260     PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE );
1261     SetEvent(*(LPHANDLE)param);
1262
1263     while (GetMessageW( &msg, 0, 0, 0 ))
1264     {
1265         UINT kbd_cnt = 0, mice_cnt = 0;
1266
1267         if (msg.message == WM_USER+0x10)
1268         {
1269             IDirectInputImpl *dinput;
1270
1271             TRACE( "Processing hook change notification lp:%ld\n", msg.lParam );
1272
1273             if (!msg.wParam && !msg.lParam)
1274             {
1275                 if (kbd_hook) UnhookWindowsHookEx( kbd_hook );
1276                 if (mouse_hook) UnhookWindowsHookEx( mouse_hook );
1277                 kbd_hook = mouse_hook = NULL;
1278                 break;
1279             }
1280
1281             EnterCriticalSection( &dinput_hook_crit );
1282
1283             /* Count acquired keyboards and mice*/
1284             LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1285             {
1286                 IDirectInputDeviceImpl *dev;
1287
1288                 EnterCriticalSection( &dinput->crit );
1289                 LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1290                 {
1291                     if (!dev->acquired || !dev->event_proc) continue;
1292
1293                     if (IsEqualGUID( &dev->guid, &GUID_SysKeyboard ) ||
1294                         IsEqualGUID( &dev->guid, &DInput_Wine_Keyboard_GUID ))
1295                         kbd_cnt++;
1296                     else
1297                         if (IsEqualGUID( &dev->guid, &GUID_SysMouse ) ||
1298                             IsEqualGUID( &dev->guid, &DInput_Wine_Mouse_GUID ))
1299                             mice_cnt++;
1300                 }
1301                 LeaveCriticalSection( &dinput->crit );
1302             }
1303             LeaveCriticalSection( &dinput_hook_crit );
1304
1305             if (kbd_cnt && !kbd_hook)
1306                 kbd_hook = SetWindowsHookExW( WH_KEYBOARD_LL, LL_hook_proc, DINPUT_instance, 0 );
1307             else if (!kbd_cnt && kbd_hook)
1308             {
1309                 UnhookWindowsHookEx( kbd_hook );
1310                 kbd_hook = NULL;
1311             }
1312
1313             if (mice_cnt && !mouse_hook)
1314                 mouse_hook = SetWindowsHookExW( WH_MOUSE_LL, LL_hook_proc, DINPUT_instance, 0 );
1315             else if (!mice_cnt && mouse_hook)
1316             {
1317                 UnhookWindowsHookEx( mouse_hook );
1318                 mouse_hook = NULL;
1319             }
1320         }
1321         TranslateMessage(&msg);
1322         DispatchMessageW(&msg);
1323     }
1324
1325     return 0;
1326 }
1327
1328 static DWORD hook_thread_id;
1329
1330 static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
1331 {
1332     0, 0, &dinput_hook_crit,
1333     { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
1334       0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
1335 };
1336 static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };
1337
1338 static BOOL check_hook_thread(void)
1339 {
1340     static HANDLE hook_thread;
1341
1342     EnterCriticalSection(&dinput_hook_crit);
1343
1344     TRACE("IDirectInputs left: %d\n", list_count(&direct_input_list));
1345     if (!list_empty(&direct_input_list) && !hook_thread)
1346     {
1347         HANDLE event;
1348
1349         event = CreateEventW(NULL, FALSE, FALSE, NULL);
1350         hook_thread = CreateThread(NULL, 0, hook_thread_proc, &event, 0, &hook_thread_id);
1351         if (event && hook_thread)
1352         {
1353             HANDLE handles[2];
1354             handles[0] = event;
1355             handles[1] = hook_thread;
1356             WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1357         }
1358         LeaveCriticalSection(&dinput_hook_crit);
1359         CloseHandle(event);
1360     }
1361     else if (list_empty(&direct_input_list) && hook_thread)
1362     {
1363         DWORD tid = hook_thread_id;
1364
1365         hook_thread_id = 0;
1366         PostThreadMessageW(tid, WM_USER+0x10, 0, 0);
1367         LeaveCriticalSection(&dinput_hook_crit);
1368
1369         /* wait for hook thread to exit */
1370         WaitForSingleObject(hook_thread, INFINITE);
1371         CloseHandle(hook_thread);
1372         hook_thread = NULL;
1373     }
1374     else
1375         LeaveCriticalSection(&dinput_hook_crit);
1376
1377     return hook_thread_id != 0;
1378 }
1379
1380 void check_dinput_hooks(LPDIRECTINPUTDEVICE8W iface)
1381 {
1382     static HHOOK callwndproc_hook;
1383     static ULONG foreground_cnt;
1384     IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8W(iface);
1385
1386     EnterCriticalSection(&dinput_hook_crit);
1387
1388     if (dev->dwCoopLevel & DISCL_FOREGROUND)
1389     {
1390         if (dev->acquired)
1391             foreground_cnt++;
1392         else
1393             foreground_cnt--;
1394     }
1395
1396     if (foreground_cnt && !callwndproc_hook)
1397         callwndproc_hook = SetWindowsHookExW( WH_CALLWNDPROC, callwndproc_proc,
1398                                               DINPUT_instance, GetCurrentThreadId() );
1399     else if (!foreground_cnt && callwndproc_hook)
1400     {
1401         UnhookWindowsHookEx( callwndproc_hook );
1402         callwndproc_hook = NULL;
1403     }
1404
1405     PostThreadMessageW( hook_thread_id, WM_USER+0x10, 1, 0 );
1406
1407     LeaveCriticalSection(&dinput_hook_crit);
1408 }