crypt32: Add additional path for Solaris 11 Express.
[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 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 /******************************************************************************
321  *      IDirectInputA_EnumDevices
322  */
323 static HRESULT WINAPI IDirectInputAImpl_EnumDevices(
324         LPDIRECTINPUT7A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
325         LPVOID pvRef, DWORD dwFlags)
326 {
327     IDirectInputImpl *This = impl_from_IDirectInput7A(iface);
328     DIDEVICEINSTANCEA devInstance;
329     unsigned int i;
330     int j, r;
331
332     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
333           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
334           lpCallback, pvRef, dwFlags);
335     _dump_EnumDevices_dwFlags(dwFlags);
336
337     if (!lpCallback)
338         return DIERR_INVALIDPARAM;
339
340     if (!This->initialized)
341         return DIERR_NOTINITIALIZED;
342
343     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
344         if (!dinput_devices[i]->enum_deviceA) continue;
345         for (j = 0, r = -1; r != 0; j++) {
346             devInstance.dwSize = sizeof(devInstance);
347             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
348             if ((r = dinput_devices[i]->enum_deviceA(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
349                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
350                     return 0;
351             }
352         }
353     }
354     
355     return 0;
356 }
357 /******************************************************************************
358  *      IDirectInputW_EnumDevices
359  */
360 static HRESULT WINAPI IDirectInputWImpl_EnumDevices(
361         LPDIRECTINPUT7W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
362         LPVOID pvRef, DWORD dwFlags) 
363 {
364     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
365     DIDEVICEINSTANCEW devInstance;
366     unsigned int i;
367     int j, r;
368
369     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
370           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
371           lpCallback, pvRef, dwFlags);
372     _dump_EnumDevices_dwFlags(dwFlags);
373
374     if (!lpCallback)
375         return DIERR_INVALIDPARAM;
376
377     if (!This->initialized)
378         return DIERR_NOTINITIALIZED;
379
380     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
381         if (!dinput_devices[i]->enum_deviceW) continue;
382         for (j = 0, r = -1; r != 0; j++) {
383             devInstance.dwSize = sizeof(devInstance);
384             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
385             if ((r = dinput_devices[i]->enum_deviceW(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
386                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
387                     return 0;
388             }
389         }
390     }
391     
392     return 0;
393 }
394
395 static ULONG WINAPI IDirectInputAImpl_AddRef(LPDIRECTINPUT7A iface)
396 {
397     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
398     ULONG ref = InterlockedIncrement(&This->ref);
399
400     TRACE( "(%p) incrementing from %d\n", This, ref - 1);
401     return ref;
402 }
403
404 static ULONG WINAPI IDirectInputWImpl_AddRef(LPDIRECTINPUT7W iface)
405 {
406     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
407     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
408 }
409
410 static ULONG WINAPI IDirectInputAImpl_Release(LPDIRECTINPUT7A iface)
411 {
412     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
413     ULONG ref = InterlockedDecrement( &This->ref );
414
415     TRACE( "(%p) releasing from %d\n", This, ref + 1 );
416
417     if (ref == 0)
418     {
419         uninitialize_directinput_instance( This );
420         HeapFree( GetProcessHeap(), 0, This );
421     }
422
423     return ref;
424 }
425
426 static ULONG WINAPI IDirectInputWImpl_Release(LPDIRECTINPUT7W iface)
427 {
428     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
429     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
430 }
431
432 static HRESULT WINAPI IDirectInputAImpl_QueryInterface(LPDIRECTINPUT7A iface, REFIID riid, LPVOID *ppobj)
433 {
434     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
435
436     TRACE( "(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppobj );
437
438     if (!riid || !ppobj)
439         return E_POINTER;
440
441     if (IsEqualGUID( &IID_IUnknown, riid ) ||
442         IsEqualGUID( &IID_IDirectInputA,  riid ) ||
443         IsEqualGUID( &IID_IDirectInput2A, riid ) ||
444         IsEqualGUID( &IID_IDirectInput7A, riid ))
445     {
446         *ppobj = &This->IDirectInput7A_iface;
447         IUnknown_AddRef( (IUnknown*)*ppobj );
448
449         return DI_OK;
450     }
451
452     if (IsEqualGUID( &IID_IDirectInputW,  riid ) ||
453         IsEqualGUID( &IID_IDirectInput2W, riid ) ||
454         IsEqualGUID( &IID_IDirectInput7W, riid ))
455     {
456         *ppobj = &This->IDirectInput7W_iface;
457         IUnknown_AddRef( (IUnknown*)*ppobj );
458
459         return DI_OK;
460     }
461
462     if (IsEqualGUID( &IID_IDirectInput8A, riid ))
463     {
464         *ppobj = &This->IDirectInput8A_iface;
465         IUnknown_AddRef( (IUnknown*)*ppobj );
466
467         return DI_OK;
468     }
469
470     if (IsEqualGUID( &IID_IDirectInput8W, riid ))
471     {
472         *ppobj = &This->IDirectInput8W_iface;
473         IUnknown_AddRef( (IUnknown*)*ppobj );
474
475         return DI_OK;
476     }
477
478     FIXME( "Unsupported interface: %s\n", debugstr_guid(riid));
479     *ppobj = NULL;
480     return E_NOINTERFACE;
481 }
482
483 static HRESULT WINAPI IDirectInputWImpl_QueryInterface(LPDIRECTINPUT7W iface, REFIID riid, LPVOID *ppobj)
484 {
485     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
486     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
487 }
488
489 static HRESULT initialize_directinput_instance(IDirectInputImpl *This, DWORD dwVersion)
490 {
491     if (!This->initialized)
492     {
493         This->dwVersion = dwVersion;
494         This->evsequence = 1;
495
496         InitializeCriticalSection( &This->crit );
497         This->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": IDirectInputImpl*->crit");
498
499         list_init( &This->devices_list );
500
501         /* Add self to the list of the IDirectInputs */
502         EnterCriticalSection( &dinput_hook_crit );
503         list_add_head( &direct_input_list, &This->entry );
504         LeaveCriticalSection( &dinput_hook_crit );
505
506         This->initialized = TRUE;
507
508         if (!check_hook_thread())
509         {
510             uninitialize_directinput_instance( This );
511             return DIERR_GENERIC;
512         }
513     }
514
515     return DI_OK;
516 }
517
518 static void uninitialize_directinput_instance(IDirectInputImpl *This)
519 {
520     if (This->initialized)
521     {
522         /* Remove self from the list of the IDirectInputs */
523         EnterCriticalSection( &dinput_hook_crit );
524         list_remove( &This->entry );
525         LeaveCriticalSection( &dinput_hook_crit );
526
527         check_hook_thread();
528
529         This->crit.DebugInfo->Spare[0] = 0;
530         DeleteCriticalSection( &This->crit );
531
532         This->initialized = FALSE;
533     }
534 }
535
536 enum directinput_versions
537 {
538     DIRECTINPUT_VERSION_300 = 0x0300,
539     DIRECTINPUT_VERSION_500 = 0x0500,
540     DIRECTINPUT_VERSION_50A = 0x050A,
541     DIRECTINPUT_VERSION_5B2 = 0x05B2,
542     DIRECTINPUT_VERSION_602 = 0x0602,
543     DIRECTINPUT_VERSION_61A = 0x061A,
544     DIRECTINPUT_VERSION_700 = 0x0700,
545 };
546
547 static HRESULT WINAPI IDirectInputAImpl_Initialize(LPDIRECTINPUT7A iface, HINSTANCE hinst, DWORD version)
548 {
549     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
550
551     TRACE("(%p)->(%p, 0x%04x)\n", iface, hinst, version);
552
553     if (!hinst)
554         return DIERR_INVALIDPARAM;
555     else if (version == 0)
556         return DIERR_NOTINITIALIZED;
557     else if (version > DIRECTINPUT_VERSION_700)
558         return DIERR_OLDDIRECTINPUTVERSION;
559     else if (version != DIRECTINPUT_VERSION_300 && version != DIRECTINPUT_VERSION_500 &&
560              version != DIRECTINPUT_VERSION_50A && version != DIRECTINPUT_VERSION_5B2 &&
561              version != DIRECTINPUT_VERSION_602 && version != DIRECTINPUT_VERSION_61A &&
562              version != DIRECTINPUT_VERSION_700 && version != DIRECTINPUT_VERSION)
563         return DIERR_BETADIRECTINPUTVERSION;
564
565     return initialize_directinput_instance(This, version);
566 }
567
568 static HRESULT WINAPI IDirectInputWImpl_Initialize(LPDIRECTINPUT7W iface, HINSTANCE hinst, DWORD x)
569 {
570     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
571     return IDirectInputAImpl_Initialize( &This->IDirectInput7A_iface, hinst, x );
572 }
573
574 static HRESULT WINAPI IDirectInputAImpl_GetDeviceStatus(LPDIRECTINPUT7A iface, REFGUID rguid)
575 {
576     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
577     HRESULT hr;
578     LPDIRECTINPUTDEVICEA device;
579
580     TRACE( "(%p)->(%s)\n", This, debugstr_guid(rguid) );
581
582     if (!This->initialized)
583         return DIERR_NOTINITIALIZED;
584
585     hr = IDirectInput_CreateDevice( iface, rguid, &device, NULL );
586     if (hr != DI_OK) return DI_NOTATTACHED;
587
588     IUnknown_Release( device );
589
590     return DI_OK;
591 }
592
593 static HRESULT WINAPI IDirectInputWImpl_GetDeviceStatus(LPDIRECTINPUT7W iface, REFGUID rguid)
594 {
595     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
596     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
597 }
598
599 static HRESULT WINAPI IDirectInputAImpl_RunControlPanel(LPDIRECTINPUT7A iface,
600                                                         HWND hwndOwner,
601                                                         DWORD dwFlags)
602 {
603     WCHAR control_exeW[] = {'c','o','n','t','r','o','l','.','e','x','e',0};
604     STARTUPINFOW si = {0};
605     PROCESS_INFORMATION pi;
606
607     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
608
609     TRACE( "(%p)->(%p, %08x)\n", This, hwndOwner, dwFlags );
610
611     if (hwndOwner && !IsWindow(hwndOwner))
612         return E_HANDLE;
613
614     if (dwFlags)
615         return DIERR_INVALIDPARAM;
616
617     if (!This->initialized)
618         return DIERR_NOTINITIALIZED;
619
620     if (!CreateProcessW(NULL, control_exeW, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
621         return HRESULT_FROM_WIN32(GetLastError());
622
623     return DI_OK;
624 }
625
626 static HRESULT WINAPI IDirectInputWImpl_RunControlPanel(LPDIRECTINPUT7W iface, HWND hwndOwner, DWORD dwFlags)
627 {
628     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
629     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
630 }
631
632 static HRESULT WINAPI IDirectInput2AImpl_FindDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
633                                                     LPCSTR pszName, LPGUID pguidInstance)
634 {
635     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
636
637     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), pszName, pguidInstance );
638
639     return DI_OK;
640 }
641
642 static HRESULT WINAPI IDirectInput2WImpl_FindDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
643                                                     LPCWSTR pszName, LPGUID pguidInstance)
644 {
645     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
646
647     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), debugstr_w(pszName), pguidInstance );
648
649     return DI_OK;
650 }
651
652 static HRESULT create_device(IDirectInputImpl *This, REFGUID rguid, REFIID riid, LPVOID *pvOut, BOOL unicode)
653 {
654     unsigned int i;
655
656     if (pvOut)
657         *pvOut = NULL;
658
659     if (!rguid || !pvOut)
660         return E_POINTER;
661
662     if (!This->initialized)
663         return DIERR_NOTINITIALIZED;
664
665     /* Loop on all the devices to see if anyone matches the given GUID */
666     for (i = 0; i < NB_DINPUT_DEVICES; i++)
667     {
668         HRESULT ret;
669
670         if (!dinput_devices[i]->create_device) continue;
671         if ((ret = dinput_devices[i]->create_device(This, rguid, riid, pvOut, unicode)) == DI_OK)
672             return DI_OK;
673     }
674
675     WARN("invalid device GUID %s\n", debugstr_guid(rguid));
676     return DIERR_DEVICENOTREG;
677 }
678
679 static HRESULT WINAPI IDirectInput7AImpl_CreateDeviceEx(LPDIRECTINPUT7A iface, REFGUID rguid,
680                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
681 {
682     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
683
684     TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
685
686     return create_device(This, rguid, riid, pvOut, FALSE);
687 }
688
689 static HRESULT WINAPI IDirectInput7WImpl_CreateDeviceEx(LPDIRECTINPUT7W iface, REFGUID rguid,
690                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
691 {
692     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
693
694     TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
695
696     return create_device(This, rguid, riid, pvOut, TRUE);
697 }
698
699 static HRESULT WINAPI IDirectInputAImpl_CreateDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
700                                                      LPDIRECTINPUTDEVICEA* pdev, LPUNKNOWN punk)
701 {
702     return IDirectInput7AImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
703 }
704
705 static HRESULT WINAPI IDirectInputWImpl_CreateDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
706                                                      LPDIRECTINPUTDEVICEW* pdev, LPUNKNOWN punk)
707 {
708     return IDirectInput7WImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
709 }
710
711 /*******************************************************************************
712  *      DirectInput8
713  */
714
715 static ULONG WINAPI IDirectInput8AImpl_AddRef(LPDIRECTINPUT8A iface)
716 {
717     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
718     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
719 }
720
721 static ULONG WINAPI IDirectInput8WImpl_AddRef(LPDIRECTINPUT8W iface)
722 {
723     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
724     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
725 }
726
727 static HRESULT WINAPI IDirectInput8AImpl_QueryInterface(LPDIRECTINPUT8A iface, REFIID riid, LPVOID *ppobj)
728 {
729     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
730     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
731 }
732
733 static HRESULT WINAPI IDirectInput8WImpl_QueryInterface(LPDIRECTINPUT8W iface, REFIID riid, LPVOID *ppobj)
734 {
735     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
736     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
737 }
738
739 static ULONG WINAPI IDirectInput8AImpl_Release(LPDIRECTINPUT8A iface)
740 {
741     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
742     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
743 }
744
745 static ULONG WINAPI IDirectInput8WImpl_Release(LPDIRECTINPUT8W iface)
746 {
747     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
748     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
749 }
750
751 static HRESULT WINAPI IDirectInput8AImpl_CreateDevice(LPDIRECTINPUT8A iface, REFGUID rguid,
752                                                       LPDIRECTINPUTDEVICE8A* pdev, LPUNKNOWN punk)
753 {
754     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
755     return IDirectInput7AImpl_CreateDeviceEx( &This->IDirectInput7A_iface, rguid, NULL, (LPVOID*)pdev, punk );
756 }
757
758 static HRESULT WINAPI IDirectInput8WImpl_CreateDevice(LPDIRECTINPUT8W iface, REFGUID rguid,
759                                                       LPDIRECTINPUTDEVICE8W* pdev, LPUNKNOWN punk)
760 {
761     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
762     return IDirectInput7WImpl_CreateDeviceEx( &This->IDirectInput7W_iface, rguid, NULL, (LPVOID*)pdev, punk );
763 }
764
765 static HRESULT WINAPI IDirectInput8AImpl_EnumDevices(LPDIRECTINPUT8A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
766                                                      LPVOID pvRef, DWORD dwFlags)
767 {
768     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
769     return IDirectInputAImpl_EnumDevices( &This->IDirectInput7A_iface, dwDevType, lpCallback, pvRef, dwFlags );
770 }
771
772 static HRESULT WINAPI IDirectInput8WImpl_EnumDevices(LPDIRECTINPUT8W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
773                                                      LPVOID pvRef, DWORD dwFlags)
774 {
775     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
776     return IDirectInputWImpl_EnumDevices( &This->IDirectInput7W_iface, dwDevType, lpCallback, pvRef, dwFlags );
777 }
778
779 static HRESULT WINAPI IDirectInput8AImpl_GetDeviceStatus(LPDIRECTINPUT8A iface, REFGUID rguid)
780 {
781     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
782     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
783 }
784
785 static HRESULT WINAPI IDirectInput8WImpl_GetDeviceStatus(LPDIRECTINPUT8W iface, REFGUID rguid)
786 {
787     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
788     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
789 }
790
791 static HRESULT WINAPI IDirectInput8AImpl_RunControlPanel(LPDIRECTINPUT8A iface, HWND hwndOwner, DWORD dwFlags)
792 {
793     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
794     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
795 }
796
797 static HRESULT WINAPI IDirectInput8WImpl_RunControlPanel(LPDIRECTINPUT8W iface, HWND hwndOwner, DWORD dwFlags)
798 {
799     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
800     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
801 }
802
803 static HRESULT WINAPI IDirectInput8AImpl_Initialize(LPDIRECTINPUT8A iface, HINSTANCE hinst, DWORD version)
804 {
805     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
806
807     TRACE("(%p)->(%p, 0x%04x)\n", iface, hinst, version);
808
809     if (!hinst)
810         return DIERR_INVALIDPARAM;
811     else if (version == 0)
812         return DIERR_NOTINITIALIZED;
813     else if (version < DIRECTINPUT_VERSION)
814         return DIERR_BETADIRECTINPUTVERSION;
815     else if (version > DIRECTINPUT_VERSION)
816         return DIERR_OLDDIRECTINPUTVERSION;
817
818     return initialize_directinput_instance(This, version);
819 }
820
821 static HRESULT WINAPI IDirectInput8WImpl_Initialize(LPDIRECTINPUT8W iface, HINSTANCE hinst, DWORD version)
822 {
823     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
824     return IDirectInput8AImpl_Initialize( &This->IDirectInput8A_iface, hinst, version );
825 }
826
827 static HRESULT WINAPI IDirectInput8AImpl_FindDevice(LPDIRECTINPUT8A iface, REFGUID rguid, LPCSTR pszName, LPGUID pguidInstance)
828 {
829     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
830     return IDirectInput2AImpl_FindDevice( &This->IDirectInput7A_iface, rguid, pszName, pguidInstance );
831 }
832
833 static HRESULT WINAPI IDirectInput8WImpl_FindDevice(LPDIRECTINPUT8W iface, REFGUID rguid, LPCWSTR pszName, LPGUID pguidInstance)
834 {
835     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
836     return IDirectInput2WImpl_FindDevice( &This->IDirectInput7W_iface, rguid, pszName, pguidInstance );
837 }
838
839 static HRESULT WINAPI IDirectInput8AImpl_EnumDevicesBySemantics(
840       LPDIRECTINPUT8A iface, LPCSTR ptszUserName, LPDIACTIONFORMATA lpdiActionFormat,
841       LPDIENUMDEVICESBYSEMANTICSCBA lpCallback,
842       LPVOID pvRef, DWORD dwFlags
843 )
844 {
845     static const REFGUID guids[2] = { &GUID_SysKeyboard, &GUID_SysMouse };
846     static const DWORD actionMasks[] = { DIKEYBOARD_MASK, DIMOUSE_MASK };
847     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
848     DIDEVICEINSTANCEA didevi;
849     LPDIRECTINPUTDEVICE8A lpdid;
850     DWORD callbackFlags;
851     int i, j;
852
853
854     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, ptszUserName, lpdiActionFormat,
855           lpCallback, pvRef, dwFlags);
856 #define X(x) if (dwFlags & x) FIXME("\tdwFlags |= "#x"\n");
857         X(DIEDBSFL_ATTACHEDONLY)
858         X(DIEDBSFL_THISUSER)
859         X(DIEDBSFL_FORCEFEEDBACK)
860         X(DIEDBSFL_AVAILABLEDEVICES)
861         X(DIEDBSFL_MULTIMICEKEYBOARDS)
862         X(DIEDBSFL_NONGAMINGDEVICES)
863 #undef X
864
865     _dump_diactionformatA(lpdiActionFormat);
866
867     didevi.dwSize = sizeof(didevi);
868
869     /* Enumerate all the joysticks */
870     for (i = 0; i < NB_DINPUT_DEVICES; i++)
871     {
872         BOOL enumSuccess;
873
874         if (!dinput_devices[i]->enum_deviceA) continue;
875
876         for (j = 0, enumSuccess = -1; enumSuccess != 0; j++)
877         {
878             TRACE(" - checking device %u ('%s')\n", i, dinput_devices[i]->name);
879
880             callbackFlags = 0;
881             /* Default behavior is to enumerate attached game controllers */
882             enumSuccess = dinput_devices[i]->enum_deviceA(DI8DEVCLASS_GAMECTRL, DIEDFL_ATTACHEDONLY | dwFlags, &didevi, This->dwVersion, j);
883             if (enumSuccess)
884             {
885                 IDirectInput_CreateDevice(iface, &didevi.guidInstance, &lpdid, NULL);
886
887                 if (lpCallback(&didevi, lpdid, callbackFlags, 0, pvRef) == DIENUM_STOP)
888                     return DI_OK;
889             }
890         }
891     }
892
893     if (dwFlags & DIEDBSFL_FORCEFEEDBACK) return DI_OK;
894
895     /* Enumerate keyboard and mouse */
896     for(i=0; i < sizeof(guids)/sizeof(guids[0]); i++)
897     {
898         callbackFlags = 0;
899
900         IDirectInput_CreateDevice(iface, guids[i], &lpdid, NULL);
901         IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
902
903         /* If there's at least one action for the device it's priority 1 */
904         for(j=0; j < lpdiActionFormat->dwActionSize; j++)
905             if ((lpdiActionFormat->rgoAction[j].dwSemantic & actionMasks[i]) == actionMasks[i])
906                 callbackFlags |= DIEDBS_MAPPEDPRI1;
907
908         if (lpCallback(&didevi, lpdid, callbackFlags, sizeof(guids)/sizeof(guids[0]) - (i+1), pvRef) == DIENUM_STOP)
909             return DI_OK;
910     }
911
912     return DI_OK;
913 }
914
915 static HRESULT WINAPI IDirectInput8WImpl_EnumDevicesBySemantics(
916       LPDIRECTINPUT8W iface, LPCWSTR ptszUserName, LPDIACTIONFORMATW lpdiActionFormat,
917       LPDIENUMDEVICESBYSEMANTICSCBW lpCallback,
918       LPVOID pvRef, DWORD dwFlags
919 )
920 {
921     static const REFGUID guids[2] = { &GUID_SysKeyboard, &GUID_SysMouse };
922     static const DWORD actionMasks[] = { DIKEYBOARD_MASK, DIMOUSE_MASK };
923     IDirectInputImpl *This = impl_from_IDirectInput8W(iface);
924     DIDEVICEINSTANCEW didevi;
925     LPDIRECTINPUTDEVICE8W lpdid;
926     DWORD callbackFlags;
927     int i, j;
928
929     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, debugstr_w(ptszUserName), lpdiActionFormat,
930           lpCallback, pvRef, dwFlags);
931
932     didevi.dwSize = sizeof(didevi);
933
934     /* Enumerate all the joysticks */
935     for (i = 0; i < NB_DINPUT_DEVICES; i++)
936     {
937         BOOL enumSuccess;
938
939         if (!dinput_devices[i]->enum_deviceW) continue;
940
941         for (j = 0, enumSuccess = -1; enumSuccess != 0; j++)
942         {
943             TRACE(" - checking device %u ('%s')\n", i, dinput_devices[i]->name);
944
945             callbackFlags = 0;
946             /* Default behavior is to enumerate attached game controllers */
947             enumSuccess = dinput_devices[i]->enum_deviceW(DI8DEVCLASS_GAMECTRL, DIEDFL_ATTACHEDONLY | dwFlags, &didevi, This->dwVersion, j);
948             if (enumSuccess)
949             {
950                 IDirectInput_CreateDevice(iface, &didevi.guidInstance, &lpdid, NULL);
951
952                 if (lpCallback(&didevi, lpdid, callbackFlags, 0, pvRef) == DIENUM_STOP)
953                     return DI_OK;
954             }
955         }
956     }
957
958     if (dwFlags & DIEDBSFL_FORCEFEEDBACK) return DI_OK;
959
960     /* Enumerate keyboard and mouse */
961     for(i=0; i < sizeof(guids)/sizeof(guids[0]); i++)
962     {
963         callbackFlags = 0;
964
965         IDirectInput_CreateDevice(iface, guids[i], &lpdid, NULL);
966         IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
967
968         /* If there's at least one action for the device it's priority 1 */
969         for(j=0; j < lpdiActionFormat->dwActionSize; j++)
970             if ((lpdiActionFormat->rgoAction[j].dwSemantic & actionMasks[i]) == actionMasks[i])
971                 callbackFlags |= DIEDBS_MAPPEDPRI1;
972
973         if (lpCallback(&didevi, lpdid, callbackFlags, sizeof(guids)/sizeof(guids[0]) - (i+1), pvRef) == DIENUM_STOP)
974             return DI_OK;
975     }
976
977     return DI_OK;
978 }
979
980 static HRESULT WINAPI IDirectInput8AImpl_ConfigureDevices(
981       LPDIRECTINPUT8A iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
982       LPDICONFIGUREDEVICESPARAMSA lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
983 )
984 {
985       IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
986
987       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
988             dwFlags, pvRefData);
989       return 0;
990 }
991
992 static HRESULT WINAPI IDirectInput8WImpl_ConfigureDevices(
993       LPDIRECTINPUT8W iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
994       LPDICONFIGUREDEVICESPARAMSW lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
995 )
996 {
997       IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
998
999       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
1000             dwFlags, pvRefData);
1001       return 0;
1002 }
1003
1004 static const IDirectInput7AVtbl ddi7avt = {
1005     IDirectInputAImpl_QueryInterface,
1006     IDirectInputAImpl_AddRef,
1007     IDirectInputAImpl_Release,
1008     IDirectInputAImpl_CreateDevice,
1009     IDirectInputAImpl_EnumDevices,
1010     IDirectInputAImpl_GetDeviceStatus,
1011     IDirectInputAImpl_RunControlPanel,
1012     IDirectInputAImpl_Initialize,
1013     IDirectInput2AImpl_FindDevice,
1014     IDirectInput7AImpl_CreateDeviceEx
1015 };
1016
1017 static const IDirectInput7WVtbl ddi7wvt = {
1018     IDirectInputWImpl_QueryInterface,
1019     IDirectInputWImpl_AddRef,
1020     IDirectInputWImpl_Release,
1021     IDirectInputWImpl_CreateDevice,
1022     IDirectInputWImpl_EnumDevices,
1023     IDirectInputWImpl_GetDeviceStatus,
1024     IDirectInputWImpl_RunControlPanel,
1025     IDirectInputWImpl_Initialize,
1026     IDirectInput2WImpl_FindDevice,
1027     IDirectInput7WImpl_CreateDeviceEx
1028 };
1029
1030 static const IDirectInput8AVtbl ddi8avt = {
1031     IDirectInput8AImpl_QueryInterface,
1032     IDirectInput8AImpl_AddRef,
1033     IDirectInput8AImpl_Release,
1034     IDirectInput8AImpl_CreateDevice,
1035     IDirectInput8AImpl_EnumDevices,
1036     IDirectInput8AImpl_GetDeviceStatus,
1037     IDirectInput8AImpl_RunControlPanel,
1038     IDirectInput8AImpl_Initialize,
1039     IDirectInput8AImpl_FindDevice,
1040     IDirectInput8AImpl_EnumDevicesBySemantics,
1041     IDirectInput8AImpl_ConfigureDevices
1042 };
1043
1044 static const IDirectInput8WVtbl ddi8wvt = {
1045     IDirectInput8WImpl_QueryInterface,
1046     IDirectInput8WImpl_AddRef,
1047     IDirectInput8WImpl_Release,
1048     IDirectInput8WImpl_CreateDevice,
1049     IDirectInput8WImpl_EnumDevices,
1050     IDirectInput8WImpl_GetDeviceStatus,
1051     IDirectInput8WImpl_RunControlPanel,
1052     IDirectInput8WImpl_Initialize,
1053     IDirectInput8WImpl_FindDevice,
1054     IDirectInput8WImpl_EnumDevicesBySemantics,
1055     IDirectInput8WImpl_ConfigureDevices
1056 };
1057
1058 /*******************************************************************************
1059  * DirectInput ClassFactory
1060  */
1061 typedef struct
1062 {
1063     /* IUnknown fields */
1064     IClassFactory IClassFactory_iface;
1065     LONG          ref;
1066 } IClassFactoryImpl;
1067
1068 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
1069 {
1070         return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
1071 }
1072
1073 static HRESULT WINAPI DICF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
1074         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1075
1076         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
1077         return E_NOINTERFACE;
1078 }
1079
1080 static ULONG WINAPI DICF_AddRef(LPCLASSFACTORY iface) {
1081         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1082         return InterlockedIncrement(&(This->ref));
1083 }
1084
1085 static ULONG WINAPI DICF_Release(LPCLASSFACTORY iface) {
1086         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1087         /* static class, won't be  freed */
1088         return InterlockedDecrement(&(This->ref));
1089 }
1090
1091 static HRESULT WINAPI DICF_CreateInstance(
1092         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
1093 ) {
1094         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1095
1096         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
1097         if ( IsEqualGUID( &IID_IUnknown, riid ) ||
1098              IsEqualGUID( &IID_IDirectInputA, riid ) ||
1099              IsEqualGUID( &IID_IDirectInputW, riid ) ||
1100              IsEqualGUID( &IID_IDirectInput2A, riid ) ||
1101              IsEqualGUID( &IID_IDirectInput2W, riid ) ||
1102              IsEqualGUID( &IID_IDirectInput7A, riid ) ||
1103              IsEqualGUID( &IID_IDirectInput7W, riid ) ) {
1104                 return create_directinput_instance(riid, ppobj, NULL);
1105         }
1106
1107         FIXME("(%p,%p,%s,%p) Interface not found!\n",This,pOuter,debugstr_guid(riid),ppobj);    
1108         return E_NOINTERFACE;
1109 }
1110
1111 static HRESULT WINAPI DICF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
1112         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1113         FIXME("(%p)->(%d),stub!\n",This,dolock);
1114         return S_OK;
1115 }
1116
1117 static const IClassFactoryVtbl DICF_Vtbl = {
1118         DICF_QueryInterface,
1119         DICF_AddRef,
1120         DICF_Release,
1121         DICF_CreateInstance,
1122         DICF_LockServer
1123 };
1124 static IClassFactoryImpl DINPUT_CF = {{&DICF_Vtbl}, 1 };
1125
1126 /***********************************************************************
1127  *              DllCanUnloadNow (DINPUT.@)
1128  */
1129 HRESULT WINAPI DllCanUnloadNow(void)
1130 {
1131     return S_FALSE;
1132 }
1133
1134 /***********************************************************************
1135  *              DllGetClassObject (DINPUT.@)
1136  */
1137 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
1138 {
1139     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1140     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
1141         *ppv = &DINPUT_CF;
1142         IClassFactory_AddRef((IClassFactory*)*ppv);
1143     return S_OK;
1144     }
1145
1146     FIXME("(%s,%s,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1147     return CLASS_E_CLASSNOTAVAILABLE;
1148 }
1149
1150 /***********************************************************************
1151  *              DllRegisterServer (DINPUT.@)
1152  */
1153 HRESULT WINAPI DllRegisterServer(void)
1154 {
1155     return __wine_register_resources( DINPUT_instance, NULL );
1156 }
1157
1158 /***********************************************************************
1159  *              DllUnregisterServer (DINPUT.@)
1160  */
1161 HRESULT WINAPI DllUnregisterServer(void)
1162 {
1163     return __wine_unregister_resources( DINPUT_instance, NULL );
1164 }
1165
1166 /******************************************************************************
1167  *      DInput hook thread
1168  */
1169
1170 static LRESULT CALLBACK LL_hook_proc( int code, WPARAM wparam, LPARAM lparam )
1171 {
1172     IDirectInputImpl *dinput;
1173     int skip = 0;
1174
1175     if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );
1176
1177     EnterCriticalSection( &dinput_hook_crit );
1178     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1179     {
1180         IDirectInputDeviceImpl *dev;
1181
1182         EnterCriticalSection( &dinput->crit );
1183         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1184             if (dev->acquired && dev->event_proc)
1185             {
1186                 TRACE("calling %p->%p (%lx %lx)\n", dev, dev->event_proc, wparam, lparam);
1187                 skip |= dev->event_proc( &dev->IDirectInputDevice8A_iface, wparam, lparam );
1188             }
1189         LeaveCriticalSection( &dinput->crit );
1190     }
1191     LeaveCriticalSection( &dinput_hook_crit );
1192
1193     return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
1194 }
1195
1196 static LRESULT CALLBACK callwndproc_proc( int code, WPARAM wparam, LPARAM lparam )
1197 {
1198     CWPSTRUCT *msg = (CWPSTRUCT *)lparam;
1199     IDirectInputImpl *dinput;
1200     HWND foreground;
1201
1202     if (code != HC_ACTION || (msg->message != WM_KILLFOCUS &&
1203         msg->message != WM_ACTIVATEAPP && msg->message != WM_ACTIVATE))
1204         return CallNextHookEx( 0, code, wparam, lparam );
1205
1206     foreground = GetForegroundWindow();
1207
1208     EnterCriticalSection( &dinput_hook_crit );
1209
1210     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1211     {
1212         IDirectInputDeviceImpl *dev;
1213
1214         EnterCriticalSection( &dinput->crit );
1215         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1216         {
1217             if (!dev->acquired) continue;
1218
1219             if (msg->hwnd == dev->win && msg->hwnd != foreground)
1220             {
1221                 TRACE( "%p window is not foreground - unacquiring %p\n", dev->win, dev );
1222                 IDirectInputDevice_Unacquire( &dev->IDirectInputDevice8A_iface );
1223             }
1224         }
1225         LeaveCriticalSection( &dinput->crit );
1226     }
1227     LeaveCriticalSection( &dinput_hook_crit );
1228
1229     return CallNextHookEx( 0, code, wparam, lparam );
1230 }
1231
1232 static DWORD WINAPI hook_thread_proc(void *param)
1233 {
1234     static HHOOK kbd_hook, mouse_hook;
1235     MSG msg;
1236
1237     /* Force creation of the message queue */
1238     PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE );
1239     SetEvent(*(LPHANDLE)param);
1240
1241     while (GetMessageW( &msg, 0, 0, 0 ))
1242     {
1243         UINT kbd_cnt = 0, mice_cnt = 0;
1244
1245         if (msg.message == WM_USER+0x10)
1246         {
1247             IDirectInputImpl *dinput;
1248
1249             TRACE( "Processing hook change notification lp:%ld\n", msg.lParam );
1250
1251             if (!msg.wParam && !msg.lParam)
1252             {
1253                 if (kbd_hook) UnhookWindowsHookEx( kbd_hook );
1254                 if (mouse_hook) UnhookWindowsHookEx( mouse_hook );
1255                 kbd_hook = mouse_hook = NULL;
1256                 break;
1257             }
1258
1259             EnterCriticalSection( &dinput_hook_crit );
1260
1261             /* Count acquired keyboards and mice*/
1262             LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1263             {
1264                 IDirectInputDeviceImpl *dev;
1265
1266                 EnterCriticalSection( &dinput->crit );
1267                 LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1268                 {
1269                     if (!dev->acquired || !dev->event_proc) continue;
1270
1271                     if (IsEqualGUID( &dev->guid, &GUID_SysKeyboard ) ||
1272                         IsEqualGUID( &dev->guid, &DInput_Wine_Keyboard_GUID ))
1273                         kbd_cnt++;
1274                     else
1275                         if (IsEqualGUID( &dev->guid, &GUID_SysMouse ) ||
1276                             IsEqualGUID( &dev->guid, &DInput_Wine_Mouse_GUID ))
1277                             mice_cnt++;
1278                 }
1279                 LeaveCriticalSection( &dinput->crit );
1280             }
1281             LeaveCriticalSection( &dinput_hook_crit );
1282
1283             if (kbd_cnt && !kbd_hook)
1284                 kbd_hook = SetWindowsHookExW( WH_KEYBOARD_LL, LL_hook_proc, DINPUT_instance, 0 );
1285             else if (!kbd_cnt && kbd_hook)
1286             {
1287                 UnhookWindowsHookEx( kbd_hook );
1288                 kbd_hook = NULL;
1289             }
1290
1291             if (mice_cnt && !mouse_hook)
1292                 mouse_hook = SetWindowsHookExW( WH_MOUSE_LL, LL_hook_proc, DINPUT_instance, 0 );
1293             else if (!mice_cnt && mouse_hook)
1294             {
1295                 UnhookWindowsHookEx( mouse_hook );
1296                 mouse_hook = NULL;
1297             }
1298         }
1299         TranslateMessage(&msg);
1300         DispatchMessageW(&msg);
1301     }
1302
1303     return 0;
1304 }
1305
1306 static DWORD hook_thread_id;
1307
1308 static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
1309 {
1310     0, 0, &dinput_hook_crit,
1311     { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
1312       0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
1313 };
1314 static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };
1315
1316 static BOOL check_hook_thread(void)
1317 {
1318     static HANDLE hook_thread;
1319
1320     EnterCriticalSection(&dinput_hook_crit);
1321
1322     TRACE("IDirectInputs left: %d\n", list_count(&direct_input_list));
1323     if (!list_empty(&direct_input_list) && !hook_thread)
1324     {
1325         HANDLE event;
1326
1327         event = CreateEventW(NULL, FALSE, FALSE, NULL);
1328         hook_thread = CreateThread(NULL, 0, hook_thread_proc, &event, 0, &hook_thread_id);
1329         if (event && hook_thread)
1330         {
1331             HANDLE handles[2];
1332             handles[0] = event;
1333             handles[1] = hook_thread;
1334             WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1335         }
1336         LeaveCriticalSection(&dinput_hook_crit);
1337         CloseHandle(event);
1338     }
1339     else if (list_empty(&direct_input_list) && hook_thread)
1340     {
1341         DWORD tid = hook_thread_id;
1342
1343         hook_thread_id = 0;
1344         PostThreadMessageW(tid, WM_USER+0x10, 0, 0);
1345         LeaveCriticalSection(&dinput_hook_crit);
1346
1347         /* wait for hook thread to exit */
1348         WaitForSingleObject(hook_thread, INFINITE);
1349         CloseHandle(hook_thread);
1350         hook_thread = NULL;
1351     }
1352     else
1353         LeaveCriticalSection(&dinput_hook_crit);
1354
1355     return hook_thread_id != 0;
1356 }
1357
1358 void check_dinput_hooks(LPDIRECTINPUTDEVICE8W iface)
1359 {
1360     static HHOOK callwndproc_hook;
1361     static ULONG foreground_cnt;
1362     IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8W(iface);
1363
1364     EnterCriticalSection(&dinput_hook_crit);
1365
1366     if (dev->dwCoopLevel & DISCL_FOREGROUND)
1367     {
1368         if (dev->acquired)
1369             foreground_cnt++;
1370         else
1371             foreground_cnt--;
1372     }
1373
1374     if (foreground_cnt && !callwndproc_hook)
1375         callwndproc_hook = SetWindowsHookExW( WH_CALLWNDPROC, callwndproc_proc,
1376                                               DINPUT_instance, GetCurrentThreadId() );
1377     else if (!foreground_cnt && callwndproc_hook)
1378     {
1379         UnhookWindowsHookEx( callwndproc_hook );
1380         callwndproc_hook = NULL;
1381     }
1382
1383     PostThreadMessageW( hook_thread_id, WM_USER+0x10, 1, 0 );
1384
1385     LeaveCriticalSection(&dinput_hook_crit);
1386 }