dinput: BuildActionMap and SetActionMap stubs for generic joystick.
[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     int i, j;
851
852
853     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, ptszUserName, lpdiActionFormat,
854           lpCallback, pvRef, dwFlags);
855 #define X(x) if (dwFlags & x) FIXME("\tdwFlags |= "#x"\n");
856         X(DIEDBSFL_ATTACHEDONLY)
857         X(DIEDBSFL_THISUSER)
858         X(DIEDBSFL_FORCEFEEDBACK)
859         X(DIEDBSFL_AVAILABLEDEVICES)
860         X(DIEDBSFL_MULTIMICEKEYBOARDS)
861         X(DIEDBSFL_NONGAMINGDEVICES)
862 #undef X
863
864     _dump_diactionformatA(lpdiActionFormat);
865
866     didevi.dwSize = sizeof(didevi);
867
868     if (dwFlags & DIEDBSFL_FORCEFEEDBACK) return DI_OK;
869
870     /* Enumerate keyboard and mouse */
871     for(i=0; i < sizeof(guids)/sizeof(guids[0]); i++)
872     {
873         DWORD callbackFlags = 0;
874
875         IDirectInput_CreateDevice(iface, guids[i], &lpdid, NULL);
876         IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
877
878         /* If there's at least one action for the device it's priority 1 */
879         for(j=0; j < lpdiActionFormat->dwActionSize; j++)
880             if ((lpdiActionFormat->rgoAction[j].dwSemantic & actionMasks[j]) == actionMasks[j])
881                 callbackFlags |= DIEDBS_MAPPEDPRI1;
882
883         if (lpCallback(&didevi, lpdid, callbackFlags, sizeof(guids)/sizeof(guids[0]) - (i+1), pvRef) == DIENUM_STOP)
884             return DI_OK;
885     }
886
887     return DI_OK;
888 }
889
890 static HRESULT WINAPI IDirectInput8WImpl_EnumDevicesBySemantics(
891       LPDIRECTINPUT8W iface, LPCWSTR ptszUserName, LPDIACTIONFORMATW lpdiActionFormat,
892       LPDIENUMDEVICESBYSEMANTICSCBW lpCallback,
893       LPVOID pvRef, DWORD dwFlags
894 )
895 {
896     static const REFGUID guids[2] = { &GUID_SysKeyboard, &GUID_SysMouse };
897     static const DWORD actionMasks[] = { DIKEYBOARD_MASK, DIMOUSE_MASK };
898     IDirectInputImpl *This = impl_from_IDirectInput8W(iface);
899     DIDEVICEINSTANCEW didevi;
900     LPDIRECTINPUTDEVICE8W lpdid;
901     int i, j;
902
903     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, debugstr_w(ptszUserName), lpdiActionFormat,
904           lpCallback, pvRef, dwFlags);
905
906     didevi.dwSize = sizeof(didevi);
907
908     if (dwFlags & DIEDBSFL_FORCEFEEDBACK) return DI_OK;
909
910     /* Enumerate keyboard and mouse */
911     for(i=0; i < sizeof(guids)/sizeof(guids[0]); i++)
912     {
913         DWORD callbackFlags = 0;
914
915         IDirectInput_CreateDevice(iface, guids[i], &lpdid, NULL);
916         IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
917
918         /* If there's at least one action for the device it's priority 1 */
919         for(j=0; j < lpdiActionFormat->dwActionSize; j++)
920             if ((lpdiActionFormat->rgoAction[j].dwSemantic & actionMasks[j]) == actionMasks[j])
921                 callbackFlags |= DIEDBS_MAPPEDPRI1;
922
923         if (lpCallback(&didevi, lpdid, callbackFlags, sizeof(guids)/sizeof(guids[0]) - (i+1), pvRef) == DIENUM_STOP)
924             return DI_OK;
925     }
926
927     return DI_OK;
928 }
929
930 static HRESULT WINAPI IDirectInput8AImpl_ConfigureDevices(
931       LPDIRECTINPUT8A iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
932       LPDICONFIGUREDEVICESPARAMSA lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
933 )
934 {
935       IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
936
937       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
938             dwFlags, pvRefData);
939       return 0;
940 }
941
942 static HRESULT WINAPI IDirectInput8WImpl_ConfigureDevices(
943       LPDIRECTINPUT8W iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
944       LPDICONFIGUREDEVICESPARAMSW lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
945 )
946 {
947       IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
948
949       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
950             dwFlags, pvRefData);
951       return 0;
952 }
953
954 static const IDirectInput7AVtbl ddi7avt = {
955     IDirectInputAImpl_QueryInterface,
956     IDirectInputAImpl_AddRef,
957     IDirectInputAImpl_Release,
958     IDirectInputAImpl_CreateDevice,
959     IDirectInputAImpl_EnumDevices,
960     IDirectInputAImpl_GetDeviceStatus,
961     IDirectInputAImpl_RunControlPanel,
962     IDirectInputAImpl_Initialize,
963     IDirectInput2AImpl_FindDevice,
964     IDirectInput7AImpl_CreateDeviceEx
965 };
966
967 static const IDirectInput7WVtbl ddi7wvt = {
968     IDirectInputWImpl_QueryInterface,
969     IDirectInputWImpl_AddRef,
970     IDirectInputWImpl_Release,
971     IDirectInputWImpl_CreateDevice,
972     IDirectInputWImpl_EnumDevices,
973     IDirectInputWImpl_GetDeviceStatus,
974     IDirectInputWImpl_RunControlPanel,
975     IDirectInputWImpl_Initialize,
976     IDirectInput2WImpl_FindDevice,
977     IDirectInput7WImpl_CreateDeviceEx
978 };
979
980 static const IDirectInput8AVtbl ddi8avt = {
981     IDirectInput8AImpl_QueryInterface,
982     IDirectInput8AImpl_AddRef,
983     IDirectInput8AImpl_Release,
984     IDirectInput8AImpl_CreateDevice,
985     IDirectInput8AImpl_EnumDevices,
986     IDirectInput8AImpl_GetDeviceStatus,
987     IDirectInput8AImpl_RunControlPanel,
988     IDirectInput8AImpl_Initialize,
989     IDirectInput8AImpl_FindDevice,
990     IDirectInput8AImpl_EnumDevicesBySemantics,
991     IDirectInput8AImpl_ConfigureDevices
992 };
993
994 static const IDirectInput8WVtbl ddi8wvt = {
995     IDirectInput8WImpl_QueryInterface,
996     IDirectInput8WImpl_AddRef,
997     IDirectInput8WImpl_Release,
998     IDirectInput8WImpl_CreateDevice,
999     IDirectInput8WImpl_EnumDevices,
1000     IDirectInput8WImpl_GetDeviceStatus,
1001     IDirectInput8WImpl_RunControlPanel,
1002     IDirectInput8WImpl_Initialize,
1003     IDirectInput8WImpl_FindDevice,
1004     IDirectInput8WImpl_EnumDevicesBySemantics,
1005     IDirectInput8WImpl_ConfigureDevices
1006 };
1007
1008 /*******************************************************************************
1009  * DirectInput ClassFactory
1010  */
1011 typedef struct
1012 {
1013     /* IUnknown fields */
1014     IClassFactory IClassFactory_iface;
1015     LONG          ref;
1016 } IClassFactoryImpl;
1017
1018 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
1019 {
1020         return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
1021 }
1022
1023 static HRESULT WINAPI DICF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
1024         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1025
1026         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
1027         return E_NOINTERFACE;
1028 }
1029
1030 static ULONG WINAPI DICF_AddRef(LPCLASSFACTORY iface) {
1031         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1032         return InterlockedIncrement(&(This->ref));
1033 }
1034
1035 static ULONG WINAPI DICF_Release(LPCLASSFACTORY iface) {
1036         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1037         /* static class, won't be  freed */
1038         return InterlockedDecrement(&(This->ref));
1039 }
1040
1041 static HRESULT WINAPI DICF_CreateInstance(
1042         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
1043 ) {
1044         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1045
1046         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
1047         if ( IsEqualGUID( &IID_IUnknown, riid ) ||
1048              IsEqualGUID( &IID_IDirectInputA, riid ) ||
1049              IsEqualGUID( &IID_IDirectInputW, riid ) ||
1050              IsEqualGUID( &IID_IDirectInput2A, riid ) ||
1051              IsEqualGUID( &IID_IDirectInput2W, riid ) ||
1052              IsEqualGUID( &IID_IDirectInput7A, riid ) ||
1053              IsEqualGUID( &IID_IDirectInput7W, riid ) ) {
1054                 return create_directinput_instance(riid, ppobj, NULL);
1055         }
1056
1057         FIXME("(%p,%p,%s,%p) Interface not found!\n",This,pOuter,debugstr_guid(riid),ppobj);    
1058         return E_NOINTERFACE;
1059 }
1060
1061 static HRESULT WINAPI DICF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
1062         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1063         FIXME("(%p)->(%d),stub!\n",This,dolock);
1064         return S_OK;
1065 }
1066
1067 static const IClassFactoryVtbl DICF_Vtbl = {
1068         DICF_QueryInterface,
1069         DICF_AddRef,
1070         DICF_Release,
1071         DICF_CreateInstance,
1072         DICF_LockServer
1073 };
1074 static IClassFactoryImpl DINPUT_CF = {{&DICF_Vtbl}, 1 };
1075
1076 /***********************************************************************
1077  *              DllCanUnloadNow (DINPUT.@)
1078  */
1079 HRESULT WINAPI DllCanUnloadNow(void)
1080 {
1081     return S_FALSE;
1082 }
1083
1084 /***********************************************************************
1085  *              DllGetClassObject (DINPUT.@)
1086  */
1087 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
1088 {
1089     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1090     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
1091         *ppv = &DINPUT_CF;
1092         IClassFactory_AddRef((IClassFactory*)*ppv);
1093     return S_OK;
1094     }
1095
1096     FIXME("(%s,%s,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1097     return CLASS_E_CLASSNOTAVAILABLE;
1098 }
1099
1100 /***********************************************************************
1101  *              DllRegisterServer (DINPUT.@)
1102  */
1103 HRESULT WINAPI DllRegisterServer(void)
1104 {
1105     return __wine_register_resources( DINPUT_instance, NULL );
1106 }
1107
1108 /***********************************************************************
1109  *              DllUnregisterServer (DINPUT.@)
1110  */
1111 HRESULT WINAPI DllUnregisterServer(void)
1112 {
1113     return __wine_unregister_resources( DINPUT_instance, NULL );
1114 }
1115
1116 /******************************************************************************
1117  *      DInput hook thread
1118  */
1119
1120 static LRESULT CALLBACK LL_hook_proc( int code, WPARAM wparam, LPARAM lparam )
1121 {
1122     IDirectInputImpl *dinput;
1123     int skip = 0;
1124
1125     if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );
1126
1127     EnterCriticalSection( &dinput_hook_crit );
1128     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1129     {
1130         IDirectInputDeviceImpl *dev;
1131
1132         EnterCriticalSection( &dinput->crit );
1133         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1134             if (dev->acquired && dev->event_proc)
1135             {
1136                 TRACE("calling %p->%p (%lx %lx)\n", dev, dev->event_proc, wparam, lparam);
1137                 skip |= dev->event_proc( &dev->IDirectInputDevice8A_iface, wparam, lparam );
1138             }
1139         LeaveCriticalSection( &dinput->crit );
1140     }
1141     LeaveCriticalSection( &dinput_hook_crit );
1142
1143     return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
1144 }
1145
1146 static LRESULT CALLBACK callwndproc_proc( int code, WPARAM wparam, LPARAM lparam )
1147 {
1148     CWPSTRUCT *msg = (CWPSTRUCT *)lparam;
1149     IDirectInputImpl *dinput;
1150     HWND foreground;
1151
1152     if (code != HC_ACTION || (msg->message != WM_KILLFOCUS &&
1153         msg->message != WM_ACTIVATEAPP && msg->message != WM_ACTIVATE))
1154         return CallNextHookEx( 0, code, wparam, lparam );
1155
1156     foreground = GetForegroundWindow();
1157
1158     EnterCriticalSection( &dinput_hook_crit );
1159
1160     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1161     {
1162         IDirectInputDeviceImpl *dev;
1163
1164         EnterCriticalSection( &dinput->crit );
1165         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1166         {
1167             if (!dev->acquired) continue;
1168
1169             if (msg->hwnd == dev->win && msg->hwnd != foreground)
1170             {
1171                 TRACE( "%p window is not foreground - unacquiring %p\n", dev->win, dev );
1172                 IDirectInputDevice_Unacquire( &dev->IDirectInputDevice8A_iface );
1173             }
1174         }
1175         LeaveCriticalSection( &dinput->crit );
1176     }
1177     LeaveCriticalSection( &dinput_hook_crit );
1178
1179     return CallNextHookEx( 0, code, wparam, lparam );
1180 }
1181
1182 static DWORD WINAPI hook_thread_proc(void *param)
1183 {
1184     static HHOOK kbd_hook, mouse_hook;
1185     MSG msg;
1186
1187     /* Force creation of the message queue */
1188     PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE );
1189     SetEvent(*(LPHANDLE)param);
1190
1191     while (GetMessageW( &msg, 0, 0, 0 ))
1192     {
1193         UINT kbd_cnt = 0, mice_cnt = 0;
1194
1195         if (msg.message == WM_USER+0x10)
1196         {
1197             IDirectInputImpl *dinput;
1198
1199             TRACE( "Processing hook change notification lp:%ld\n", msg.lParam );
1200
1201             if (!msg.wParam && !msg.lParam)
1202             {
1203                 if (kbd_hook) UnhookWindowsHookEx( kbd_hook );
1204                 if (mouse_hook) UnhookWindowsHookEx( mouse_hook );
1205                 kbd_hook = mouse_hook = NULL;
1206                 break;
1207             }
1208
1209             EnterCriticalSection( &dinput_hook_crit );
1210
1211             /* Count acquired keyboards and mice*/
1212             LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1213             {
1214                 IDirectInputDeviceImpl *dev;
1215
1216                 EnterCriticalSection( &dinput->crit );
1217                 LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1218                 {
1219                     if (!dev->acquired || !dev->event_proc) continue;
1220
1221                     if (IsEqualGUID( &dev->guid, &GUID_SysKeyboard ) ||
1222                         IsEqualGUID( &dev->guid, &DInput_Wine_Keyboard_GUID ))
1223                         kbd_cnt++;
1224                     else
1225                         if (IsEqualGUID( &dev->guid, &GUID_SysMouse ) ||
1226                             IsEqualGUID( &dev->guid, &DInput_Wine_Mouse_GUID ))
1227                             mice_cnt++;
1228                 }
1229                 LeaveCriticalSection( &dinput->crit );
1230             }
1231             LeaveCriticalSection( &dinput_hook_crit );
1232
1233             if (kbd_cnt && !kbd_hook)
1234                 kbd_hook = SetWindowsHookExW( WH_KEYBOARD_LL, LL_hook_proc, DINPUT_instance, 0 );
1235             else if (!kbd_cnt && kbd_hook)
1236             {
1237                 UnhookWindowsHookEx( kbd_hook );
1238                 kbd_hook = NULL;
1239             }
1240
1241             if (mice_cnt && !mouse_hook)
1242                 mouse_hook = SetWindowsHookExW( WH_MOUSE_LL, LL_hook_proc, DINPUT_instance, 0 );
1243             else if (!mice_cnt && mouse_hook)
1244             {
1245                 UnhookWindowsHookEx( mouse_hook );
1246                 mouse_hook = NULL;
1247             }
1248         }
1249         TranslateMessage(&msg);
1250         DispatchMessageW(&msg);
1251     }
1252
1253     return 0;
1254 }
1255
1256 static DWORD hook_thread_id;
1257
1258 static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
1259 {
1260     0, 0, &dinput_hook_crit,
1261     { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
1262       0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
1263 };
1264 static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };
1265
1266 static BOOL check_hook_thread(void)
1267 {
1268     static HANDLE hook_thread;
1269
1270     EnterCriticalSection(&dinput_hook_crit);
1271
1272     TRACE("IDirectInputs left: %d\n", list_count(&direct_input_list));
1273     if (!list_empty(&direct_input_list) && !hook_thread)
1274     {
1275         HANDLE event;
1276
1277         event = CreateEventW(NULL, FALSE, FALSE, NULL);
1278         hook_thread = CreateThread(NULL, 0, hook_thread_proc, &event, 0, &hook_thread_id);
1279         if (event && hook_thread)
1280         {
1281             HANDLE handles[2];
1282             handles[0] = event;
1283             handles[1] = hook_thread;
1284             WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1285         }
1286         LeaveCriticalSection(&dinput_hook_crit);
1287         CloseHandle(event);
1288     }
1289     else if (list_empty(&direct_input_list) && hook_thread)
1290     {
1291         DWORD tid = hook_thread_id;
1292
1293         hook_thread_id = 0;
1294         PostThreadMessageW(tid, WM_USER+0x10, 0, 0);
1295         LeaveCriticalSection(&dinput_hook_crit);
1296
1297         /* wait for hook thread to exit */
1298         WaitForSingleObject(hook_thread, INFINITE);
1299         CloseHandle(hook_thread);
1300         hook_thread = NULL;
1301     }
1302     else
1303         LeaveCriticalSection(&dinput_hook_crit);
1304
1305     return hook_thread_id != 0;
1306 }
1307
1308 void check_dinput_hooks(LPDIRECTINPUTDEVICE8W iface)
1309 {
1310     static HHOOK callwndproc_hook;
1311     static ULONG foreground_cnt;
1312     IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8W(iface);
1313
1314     EnterCriticalSection(&dinput_hook_crit);
1315
1316     if (dev->dwCoopLevel & DISCL_FOREGROUND)
1317     {
1318         if (dev->acquired)
1319             foreground_cnt++;
1320         else
1321             foreground_cnt--;
1322     }
1323
1324     if (foreground_cnt && !callwndproc_hook)
1325         callwndproc_hook = SetWindowsHookExW( WH_CALLWNDPROC, callwndproc_proc,
1326                                               DINPUT_instance, GetCurrentThreadId() );
1327     else if (!foreground_cnt && callwndproc_hook)
1328     {
1329         UnhookWindowsHookEx( callwndproc_hook );
1330         callwndproc_hook = NULL;
1331     }
1332
1333     PostThreadMessageW( hook_thread_id, WM_USER+0x10, 1, 0 );
1334
1335     LeaveCriticalSection(&dinput_hook_crit);
1336 }