wiaservc: COM cleanup for the IWiaDevMgr iface.
[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 /******************************************************************************
119  *      DirectInputCreateEx (DINPUT.@)
120  */
121 HRESULT WINAPI DirectInputCreateEx(
122         HINSTANCE hinst, DWORD dwVersion, REFIID riid, LPVOID *ppDI,
123         LPUNKNOWN punkOuter) 
124 {
125     IDirectInputImpl* This;
126
127     TRACE("(%p,%04x,%s,%p,%p)\n", hinst, dwVersion, debugstr_guid(riid), ppDI, punkOuter);
128
129     if (IsEqualGUID( &IID_IUnknown,       riid ) ||
130         IsEqualGUID( &IID_IDirectInputA,  riid ) ||
131         IsEqualGUID( &IID_IDirectInput2A, riid ) ||
132         IsEqualGUID( &IID_IDirectInput7A, riid ) ||
133         IsEqualGUID( &IID_IDirectInputW,  riid ) ||
134         IsEqualGUID( &IID_IDirectInput2W, riid ) ||
135         IsEqualGUID( &IID_IDirectInput7W, riid ) ||
136         IsEqualGUID( &IID_IDirectInput8A, riid ) ||
137         IsEqualGUID( &IID_IDirectInput8W, riid ))
138     {
139         if (!(This = HeapAlloc( GetProcessHeap(), 0, sizeof(IDirectInputImpl) )))
140             return DIERR_OUTOFMEMORY;
141     }
142     else
143         return DIERR_OLDDIRECTINPUTVERSION;
144
145     This->IDirectInput7A_iface.lpVtbl = &ddi7avt;
146     This->IDirectInput7W_iface.lpVtbl = &ddi7wvt;
147     This->IDirectInput8A_iface.lpVtbl = &ddi8avt;
148     This->IDirectInput8W_iface.lpVtbl = &ddi8wvt;
149     This->ref         = 0;
150     This->dwVersion   = dwVersion;
151     This->evsequence  = 1;
152
153     InitializeCriticalSection(&This->crit);
154     This->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": IDirectInputImpl*->crit");
155
156     list_init( &This->devices_list );
157
158     /* Add self to the list of the IDirectInputs */
159     EnterCriticalSection( &dinput_hook_crit );
160     list_add_head( &direct_input_list, &This->entry );
161     LeaveCriticalSection( &dinput_hook_crit );
162
163     if (!check_hook_thread())
164     {
165         IUnknown_Release( &This->IDirectInput7A_iface );
166         return DIERR_GENERIC;
167     }
168
169     IDirectInput_QueryInterface( &This->IDirectInput7A_iface, riid, ppDI );
170     return DI_OK;
171 }
172
173 /******************************************************************************
174  *      DirectInputCreateA (DINPUT.@)
175  */
176 HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateA(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA *ppDI, LPUNKNOWN punkOuter)
177 {
178     return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7A, (LPVOID *)ppDI, punkOuter);
179 }
180
181 /******************************************************************************
182  *      DirectInputCreateW (DINPUT.@)
183  */
184 HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateW(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTW *ppDI, LPUNKNOWN punkOuter)
185 {
186     return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7W, (LPVOID *)ppDI, punkOuter);
187 }
188
189 static const char *_dump_DIDEVTYPE_value(DWORD dwDevType) {
190     switch (dwDevType) {
191         case 0: return "All devices";
192         case DIDEVTYPE_MOUSE: return "DIDEVTYPE_MOUSE";
193         case DIDEVTYPE_KEYBOARD: return "DIDEVTYPE_KEYBOARD";
194         case DIDEVTYPE_JOYSTICK: return "DIDEVTYPE_JOYSTICK";
195         case DIDEVTYPE_DEVICE: return "DIDEVTYPE_DEVICE";
196         default: return "Unknown";
197     }
198 }
199
200 static void _dump_EnumDevices_dwFlags(DWORD dwFlags) {
201     if (TRACE_ON(dinput)) {
202         unsigned int   i;
203         static const struct {
204             DWORD       mask;
205             const char  *name;
206         } flags[] = {
207 #define FE(x) { x, #x}
208             FE(DIEDFL_ALLDEVICES),
209             FE(DIEDFL_ATTACHEDONLY),
210             FE(DIEDFL_FORCEFEEDBACK),
211             FE(DIEDFL_INCLUDEALIASES),
212             FE(DIEDFL_INCLUDEPHANTOMS)
213 #undef FE
214         };
215         TRACE(" flags: ");
216         if (dwFlags == 0) {
217             TRACE("DIEDFL_ALLDEVICES\n");
218             return;
219         }
220         for (i = 0; i < (sizeof(flags) / sizeof(flags[0])); i++)
221             if (flags[i].mask & dwFlags)
222                 TRACE("%s ",flags[i].name);
223     }
224     TRACE("\n");
225 }
226
227 void _dump_diactionformatA(LPDIACTIONFORMATA lpdiActionFormat) {
228     unsigned int i;
229
230     FIXME("diaf.dwSize = %d\n", lpdiActionFormat->dwSize);
231     FIXME("diaf.dwActionSize = %d\n", lpdiActionFormat->dwActionSize);
232     FIXME("diaf.dwDataSize = %d\n", lpdiActionFormat->dwDataSize);
233     FIXME("diaf.dwNumActions = %d\n", lpdiActionFormat->dwNumActions);
234     FIXME("diaf.rgoAction = %p\n", lpdiActionFormat->rgoAction);
235     FIXME("diaf.guidActionMap = %s\n", debugstr_guid(&lpdiActionFormat->guidActionMap));
236     FIXME("diaf.dwGenre = 0x%08x\n", lpdiActionFormat->dwGenre);
237     FIXME("diaf.dwBufferSize = %d\n", lpdiActionFormat->dwBufferSize);
238     FIXME("diaf.lAxisMin = %d\n", lpdiActionFormat->lAxisMin);
239     FIXME("diaf.lAxisMax = %d\n", lpdiActionFormat->lAxisMax);
240     FIXME("diaf.hInstString = %p\n", lpdiActionFormat->hInstString);
241     FIXME("diaf.ftTimeStamp ...\n");
242     FIXME("diaf.dwCRC = 0x%x\n", lpdiActionFormat->dwCRC);
243     FIXME("diaf.tszActionMap = %s\n", debugstr_a(lpdiActionFormat->tszActionMap));
244     for (i = 0; i < lpdiActionFormat->dwNumActions; i++)
245     {
246         FIXME("diaf.rgoAction[%u]:\n", i);
247         FIXME("\tuAppData=0x%lx\n", lpdiActionFormat->rgoAction[i].uAppData);
248         FIXME("\tdwSemantic=0x%08x\n", lpdiActionFormat->rgoAction[i].dwSemantic);
249         FIXME("\tdwFlags=0x%x\n", lpdiActionFormat->rgoAction[i].dwFlags);
250         FIXME("\tszActionName=%s\n", debugstr_a(lpdiActionFormat->rgoAction[i].u.lptszActionName));
251         FIXME("\tguidInstance=%s\n", debugstr_guid(&lpdiActionFormat->rgoAction[i].guidInstance));
252         FIXME("\tdwObjID=0x%x\n", lpdiActionFormat->rgoAction[i].dwObjID);
253         FIXME("\tdwHow=0x%x\n", lpdiActionFormat->rgoAction[i].dwHow);
254     }
255 }
256
257 /******************************************************************************
258  *      IDirectInputA_EnumDevices
259  */
260 static HRESULT WINAPI IDirectInputAImpl_EnumDevices(
261         LPDIRECTINPUT7A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
262         LPVOID pvRef, DWORD dwFlags)
263 {
264     IDirectInputImpl *This = impl_from_IDirectInput7A(iface);
265     DIDEVICEINSTANCEA devInstance;
266     unsigned int i;
267     int j, r;
268
269     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
270           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
271           lpCallback, pvRef, dwFlags);
272     _dump_EnumDevices_dwFlags(dwFlags);
273
274     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
275         if (!dinput_devices[i]->enum_deviceA) continue;
276         for (j = 0, r = -1; r != 0; j++) {
277             devInstance.dwSize = sizeof(devInstance);
278             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
279             if ((r = dinput_devices[i]->enum_deviceA(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
280                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
281                     return 0;
282             }
283         }
284     }
285     
286     return 0;
287 }
288 /******************************************************************************
289  *      IDirectInputW_EnumDevices
290  */
291 static HRESULT WINAPI IDirectInputWImpl_EnumDevices(
292         LPDIRECTINPUT7W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
293         LPVOID pvRef, DWORD dwFlags) 
294 {
295     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
296     DIDEVICEINSTANCEW devInstance;
297     unsigned int i;
298     int j, r;
299
300     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
301           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
302           lpCallback, pvRef, dwFlags);
303     _dump_EnumDevices_dwFlags(dwFlags);
304
305     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
306         if (!dinput_devices[i]->enum_deviceW) continue;
307         for (j = 0, r = -1; r != 0; j++) {
308             devInstance.dwSize = sizeof(devInstance);
309             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
310             if ((r = dinput_devices[i]->enum_deviceW(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
311                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
312                     return 0;
313             }
314         }
315     }
316     
317     return 0;
318 }
319
320 static ULONG WINAPI IDirectInputAImpl_AddRef(LPDIRECTINPUT7A iface)
321 {
322     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
323     ULONG ref = InterlockedIncrement(&This->ref);
324
325     TRACE( "(%p) incrementing from %d\n", This, ref - 1);
326     return ref;
327 }
328
329 static ULONG WINAPI IDirectInputWImpl_AddRef(LPDIRECTINPUT7W iface)
330 {
331     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
332     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
333 }
334
335 static ULONG WINAPI IDirectInputAImpl_Release(LPDIRECTINPUT7A iface)
336 {
337     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
338     ULONG ref = InterlockedDecrement( &This->ref );
339
340     TRACE( "(%p) releasing from %d\n", This, ref + 1 );
341
342     if (ref) return ref;
343
344     /* Remove self from the list of the IDirectInputs */
345     EnterCriticalSection( &dinput_hook_crit );
346     list_remove( &This->entry );
347     LeaveCriticalSection( &dinput_hook_crit );
348
349     check_hook_thread();
350
351     This->crit.DebugInfo->Spare[0] = 0;
352     DeleteCriticalSection( &This->crit );
353     HeapFree( GetProcessHeap(), 0, This );
354
355     return 0;
356 }
357
358 static ULONG WINAPI IDirectInputWImpl_Release(LPDIRECTINPUT7W iface)
359 {
360     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
361     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
362 }
363
364 static HRESULT WINAPI IDirectInputAImpl_QueryInterface(LPDIRECTINPUT7A iface, REFIID riid, LPVOID *ppobj)
365 {
366     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
367
368     TRACE( "(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppobj );
369
370     if (IsEqualGUID( &IID_IUnknown, riid ) ||
371         IsEqualGUID( &IID_IDirectInputA,  riid ) ||
372         IsEqualGUID( &IID_IDirectInput2A, riid ) ||
373         IsEqualGUID( &IID_IDirectInput7A, riid ))
374     {
375         *ppobj = &This->IDirectInput7A_iface;
376         IUnknown_AddRef( (IUnknown*)*ppobj );
377
378         return DI_OK;
379     }
380
381     if (IsEqualGUID( &IID_IDirectInputW,  riid ) ||
382         IsEqualGUID( &IID_IDirectInput2W, riid ) ||
383         IsEqualGUID( &IID_IDirectInput7W, riid ))
384     {
385         *ppobj = &This->IDirectInput7W_iface;
386         IUnknown_AddRef( (IUnknown*)*ppobj );
387
388         return DI_OK;
389     }
390
391     if (IsEqualGUID( &IID_IDirectInput8A, riid ))
392     {
393         *ppobj = &This->IDirectInput8A_iface;
394         IUnknown_AddRef( (IUnknown*)*ppobj );
395
396         return DI_OK;
397     }
398
399     if (IsEqualGUID( &IID_IDirectInput8W, riid ))
400     {
401         *ppobj = &This->IDirectInput8W_iface;
402         IUnknown_AddRef( (IUnknown*)*ppobj );
403
404         return DI_OK;
405     }
406
407     FIXME( "Unsupported interface: %s\n", debugstr_guid(riid));
408     return E_FAIL;
409 }
410
411 static HRESULT WINAPI IDirectInputWImpl_QueryInterface(LPDIRECTINPUT7W iface, REFIID riid, LPVOID *ppobj)
412 {
413     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
414     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
415 }
416
417 static HRESULT WINAPI IDirectInputAImpl_Initialize(LPDIRECTINPUT7A iface, HINSTANCE hinst, DWORD x) {
418         TRACE("(this=%p,%p,%x)\n",iface, hinst, x);
419         
420         /* Initialize can return: DIERR_BETADIRECTINPUTVERSION, DIERR_OLDDIRECTINPUTVERSION and DI_OK.
421          * Since we already initialized the device, return DI_OK. In the past we returned DIERR_ALREADYINITIALIZED
422          * which broke applications like Tomb Raider Legend because it isn't a legal return value.
423          */
424         return DI_OK;
425 }
426
427 static HRESULT WINAPI IDirectInputWImpl_Initialize(LPDIRECTINPUT7W iface, HINSTANCE hinst, DWORD x)
428 {
429     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
430     return IDirectInputAImpl_Initialize( &This->IDirectInput7A_iface, hinst, x );
431 }
432
433 static HRESULT WINAPI IDirectInputAImpl_GetDeviceStatus(LPDIRECTINPUT7A iface, REFGUID rguid)
434 {
435     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
436     HRESULT hr;
437     LPDIRECTINPUTDEVICEA device;
438
439     TRACE( "(%p)->(%s)\n", This, debugstr_guid(rguid) );
440
441     hr = IDirectInput_CreateDevice( iface, rguid, &device, NULL );
442     if (hr != DI_OK) return DI_NOTATTACHED;
443
444     IUnknown_Release( device );
445
446     return DI_OK;
447 }
448
449 static HRESULT WINAPI IDirectInputWImpl_GetDeviceStatus(LPDIRECTINPUT7W iface, REFGUID rguid)
450 {
451     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
452     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
453 }
454
455 static HRESULT WINAPI IDirectInputAImpl_RunControlPanel(LPDIRECTINPUT7A iface,
456                                                         HWND hwndOwner,
457                                                         DWORD dwFlags)
458 {
459     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
460
461     FIXME( "(%p)->(%p,%08x): stub\n", This, hwndOwner, dwFlags );
462
463     return DI_OK;
464 }
465
466 static HRESULT WINAPI IDirectInputWImpl_RunControlPanel(LPDIRECTINPUT7W iface, HWND hwndOwner, DWORD dwFlags)
467 {
468     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
469     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
470 }
471
472 static HRESULT WINAPI IDirectInput2AImpl_FindDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
473                                                     LPCSTR pszName, LPGUID pguidInstance)
474 {
475     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
476
477     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), pszName, pguidInstance );
478
479     return DI_OK;
480 }
481
482 static HRESULT WINAPI IDirectInput2WImpl_FindDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
483                                                     LPCWSTR pszName, LPGUID pguidInstance)
484 {
485     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
486
487     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), debugstr_w(pszName), pguidInstance );
488
489     return DI_OK;
490 }
491
492 static HRESULT WINAPI IDirectInput7AImpl_CreateDeviceEx(LPDIRECTINPUT7A iface, REFGUID rguid,
493                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
494 {
495   IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
496   HRESULT ret_value = DIERR_DEVICENOTREG;
497   unsigned int i;
498
499   TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
500
501   if (!rguid || !pvOut) return E_POINTER;
502
503   /* Loop on all the devices to see if anyone matches the given GUID */
504   for (i = 0; i < NB_DINPUT_DEVICES; i++) {
505     HRESULT ret;
506
507     if (!dinput_devices[i]->create_deviceA) continue;
508     if ((ret = dinput_devices[i]->create_deviceA(This, rguid, riid, (LPDIRECTINPUTDEVICEA*) pvOut)) == DI_OK)
509     {
510       IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8A(*pvOut);
511
512       EnterCriticalSection( &This->crit );
513       list_add_tail( &This->devices_list, &dev->entry );
514       LeaveCriticalSection( &This->crit );
515       return DI_OK;
516     }
517
518     if (ret == DIERR_NOINTERFACE)
519       ret_value = DIERR_NOINTERFACE;
520   }
521
522   if (ret_value == DIERR_NOINTERFACE)
523   {
524     WARN("invalid device GUID %s\n", debugstr_guid(rguid));
525   }
526
527   return ret_value;
528 }
529
530 static HRESULT WINAPI IDirectInput7WImpl_CreateDeviceEx(LPDIRECTINPUT7W iface, REFGUID rguid,
531                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
532 {
533   IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
534   HRESULT ret_value = DIERR_DEVICENOTREG;
535   unsigned int i;
536
537   TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
538
539   if (!rguid || !pvOut) return E_POINTER;
540
541   /* Loop on all the devices to see if anyone matches the given GUID */
542   for (i = 0; i < NB_DINPUT_DEVICES; i++) {
543     HRESULT ret;
544
545     if (!dinput_devices[i]->create_deviceW) continue;
546     if ((ret = dinput_devices[i]->create_deviceW(This, rguid, riid, (LPDIRECTINPUTDEVICEW*) pvOut)) == DI_OK)
547     {
548       IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8W(*pvOut);
549
550       EnterCriticalSection( &This->crit );
551       list_add_tail( &This->devices_list, &dev->entry );
552       LeaveCriticalSection( &This->crit );
553       return DI_OK;
554     }
555
556     if (ret == DIERR_NOINTERFACE)
557       ret_value = DIERR_NOINTERFACE;
558   }
559
560   return ret_value;
561 }
562
563 static HRESULT WINAPI IDirectInputAImpl_CreateDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
564                                                      LPDIRECTINPUTDEVICEA* pdev, LPUNKNOWN punk)
565 {
566     return IDirectInput7AImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
567 }
568
569 static HRESULT WINAPI IDirectInputWImpl_CreateDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
570                                                      LPDIRECTINPUTDEVICEW* pdev, LPUNKNOWN punk)
571 {
572     return IDirectInput7WImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
573 }
574
575 /*******************************************************************************
576  *      DirectInput8
577  */
578
579 static ULONG WINAPI IDirectInput8AImpl_AddRef(LPDIRECTINPUT8A iface)
580 {
581     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
582     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
583 }
584
585 static ULONG WINAPI IDirectInput8WImpl_AddRef(LPDIRECTINPUT8W iface)
586 {
587     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
588     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
589 }
590
591 static HRESULT WINAPI IDirectInput8AImpl_QueryInterface(LPDIRECTINPUT8A iface, REFIID riid, LPVOID *ppobj)
592 {
593     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
594     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
595 }
596
597 static HRESULT WINAPI IDirectInput8WImpl_QueryInterface(LPDIRECTINPUT8W iface, REFIID riid, LPVOID *ppobj)
598 {
599     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
600     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
601 }
602
603 static ULONG WINAPI IDirectInput8AImpl_Release(LPDIRECTINPUT8A iface)
604 {
605     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
606     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
607 }
608
609 static ULONG WINAPI IDirectInput8WImpl_Release(LPDIRECTINPUT8W iface)
610 {
611     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
612     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
613 }
614
615 static HRESULT WINAPI IDirectInput8AImpl_CreateDevice(LPDIRECTINPUT8A iface, REFGUID rguid,
616                                                       LPDIRECTINPUTDEVICE8A* pdev, LPUNKNOWN punk)
617 {
618     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
619     return IDirectInput7AImpl_CreateDeviceEx( &This->IDirectInput7A_iface, rguid, NULL, (LPVOID*)pdev, punk );
620 }
621
622 static HRESULT WINAPI IDirectInput8WImpl_CreateDevice(LPDIRECTINPUT8W iface, REFGUID rguid,
623                                                       LPDIRECTINPUTDEVICE8W* pdev, LPUNKNOWN punk)
624 {
625     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
626     return IDirectInput7WImpl_CreateDeviceEx( &This->IDirectInput7W_iface, rguid, NULL, (LPVOID*)pdev, punk );
627 }
628
629 static HRESULT WINAPI IDirectInput8AImpl_EnumDevices(LPDIRECTINPUT8A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
630                                                      LPVOID pvRef, DWORD dwFlags)
631 {
632     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
633     return IDirectInputAImpl_EnumDevices( &This->IDirectInput7A_iface, dwDevType, lpCallback, pvRef, dwFlags );
634 }
635
636 static HRESULT WINAPI IDirectInput8WImpl_EnumDevices(LPDIRECTINPUT8W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
637                                                      LPVOID pvRef, DWORD dwFlags)
638 {
639     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
640     return IDirectInputWImpl_EnumDevices( &This->IDirectInput7W_iface, dwDevType, lpCallback, pvRef, dwFlags );
641 }
642
643 static HRESULT WINAPI IDirectInput8AImpl_GetDeviceStatus(LPDIRECTINPUT8A iface, REFGUID rguid)
644 {
645     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
646     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
647 }
648
649 static HRESULT WINAPI IDirectInput8WImpl_GetDeviceStatus(LPDIRECTINPUT8W iface, REFGUID rguid)
650 {
651     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
652     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
653 }
654
655 static HRESULT WINAPI IDirectInput8AImpl_RunControlPanel(LPDIRECTINPUT8A iface, HWND hwndOwner, DWORD dwFlags)
656 {
657     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
658     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
659 }
660
661 static HRESULT WINAPI IDirectInput8WImpl_RunControlPanel(LPDIRECTINPUT8W iface, HWND hwndOwner, DWORD dwFlags)
662 {
663     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
664     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
665 }
666
667 static HRESULT WINAPI IDirectInput8AImpl_Initialize(LPDIRECTINPUT8A iface, HINSTANCE hinst, DWORD x)
668 {
669     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
670     return IDirectInputAImpl_Initialize( &This->IDirectInput7A_iface, hinst, x );
671 }
672
673 static HRESULT WINAPI IDirectInput8WImpl_Initialize(LPDIRECTINPUT8W iface, HINSTANCE hinst, DWORD x)
674 {
675     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
676     return IDirectInputAImpl_Initialize( &This->IDirectInput7A_iface, hinst, x );
677 }
678
679 static HRESULT WINAPI IDirectInput8AImpl_FindDevice(LPDIRECTINPUT8A iface, REFGUID rguid, LPCSTR pszName, LPGUID pguidInstance)
680 {
681     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
682     return IDirectInput2AImpl_FindDevice( &This->IDirectInput7A_iface, rguid, pszName, pguidInstance );
683 }
684
685 static HRESULT WINAPI IDirectInput8WImpl_FindDevice(LPDIRECTINPUT8W iface, REFGUID rguid, LPCWSTR pszName, LPGUID pguidInstance)
686 {
687     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
688     return IDirectInput2WImpl_FindDevice( &This->IDirectInput7W_iface, rguid, pszName, pguidInstance );
689 }
690
691 static HRESULT WINAPI IDirectInput8AImpl_EnumDevicesBySemantics(
692       LPDIRECTINPUT8A iface, LPCSTR ptszUserName, LPDIACTIONFORMATA lpdiActionFormat,
693       LPDIENUMDEVICESBYSEMANTICSCBA lpCallback,
694       LPVOID pvRef, DWORD dwFlags
695 )
696 {
697     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
698
699     FIXME("(this=%p,%s,%p,%p,%p,%04x): stub\n", This, ptszUserName, lpdiActionFormat,
700           lpCallback, pvRef, dwFlags);
701 #define X(x) if (dwFlags & x) FIXME("\tdwFlags |= "#x"\n");
702         X(DIEDBSFL_ATTACHEDONLY)
703         X(DIEDBSFL_THISUSER)
704         X(DIEDBSFL_FORCEFEEDBACK)
705         X(DIEDBSFL_AVAILABLEDEVICES)
706         X(DIEDBSFL_MULTIMICEKEYBOARDS)
707         X(DIEDBSFL_NONGAMINGDEVICES)
708 #undef X
709
710     _dump_diactionformatA(lpdiActionFormat);
711
712     return DI_OK;
713 }
714
715 static HRESULT WINAPI IDirectInput8WImpl_EnumDevicesBySemantics(
716       LPDIRECTINPUT8W iface, LPCWSTR ptszUserName, LPDIACTIONFORMATW lpdiActionFormat,
717       LPDIENUMDEVICESBYSEMANTICSCBW lpCallback,
718       LPVOID pvRef, DWORD dwFlags
719 )
720 {
721       IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
722
723       FIXME("(this=%p,%s,%p,%p,%p,%04x): stub\n", This, debugstr_w(ptszUserName), lpdiActionFormat,
724             lpCallback, pvRef, dwFlags);
725       return 0;
726 }
727
728 static HRESULT WINAPI IDirectInput8AImpl_ConfigureDevices(
729       LPDIRECTINPUT8A iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
730       LPDICONFIGUREDEVICESPARAMSA lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
731 )
732 {
733       IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
734
735       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
736             dwFlags, pvRefData);
737       return 0;
738 }
739
740 static HRESULT WINAPI IDirectInput8WImpl_ConfigureDevices(
741       LPDIRECTINPUT8W iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
742       LPDICONFIGUREDEVICESPARAMSW lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
743 )
744 {
745       IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
746
747       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
748             dwFlags, pvRefData);
749       return 0;
750 }
751
752 static const IDirectInput7AVtbl ddi7avt = {
753     IDirectInputAImpl_QueryInterface,
754     IDirectInputAImpl_AddRef,
755     IDirectInputAImpl_Release,
756     IDirectInputAImpl_CreateDevice,
757     IDirectInputAImpl_EnumDevices,
758     IDirectInputAImpl_GetDeviceStatus,
759     IDirectInputAImpl_RunControlPanel,
760     IDirectInputAImpl_Initialize,
761     IDirectInput2AImpl_FindDevice,
762     IDirectInput7AImpl_CreateDeviceEx
763 };
764
765 static const IDirectInput7WVtbl ddi7wvt = {
766     IDirectInputWImpl_QueryInterface,
767     IDirectInputWImpl_AddRef,
768     IDirectInputWImpl_Release,
769     IDirectInputWImpl_CreateDevice,
770     IDirectInputWImpl_EnumDevices,
771     IDirectInputWImpl_GetDeviceStatus,
772     IDirectInputWImpl_RunControlPanel,
773     IDirectInputWImpl_Initialize,
774     IDirectInput2WImpl_FindDevice,
775     IDirectInput7WImpl_CreateDeviceEx
776 };
777
778 static const IDirectInput8AVtbl ddi8avt = {
779     IDirectInput8AImpl_QueryInterface,
780     IDirectInput8AImpl_AddRef,
781     IDirectInput8AImpl_Release,
782     IDirectInput8AImpl_CreateDevice,
783     IDirectInput8AImpl_EnumDevices,
784     IDirectInput8AImpl_GetDeviceStatus,
785     IDirectInput8AImpl_RunControlPanel,
786     IDirectInput8AImpl_Initialize,
787     IDirectInput8AImpl_FindDevice,
788     IDirectInput8AImpl_EnumDevicesBySemantics,
789     IDirectInput8AImpl_ConfigureDevices
790 };
791
792 static const IDirectInput8WVtbl ddi8wvt = {
793     IDirectInput8WImpl_QueryInterface,
794     IDirectInput8WImpl_AddRef,
795     IDirectInput8WImpl_Release,
796     IDirectInput8WImpl_CreateDevice,
797     IDirectInput8WImpl_EnumDevices,
798     IDirectInput8WImpl_GetDeviceStatus,
799     IDirectInput8WImpl_RunControlPanel,
800     IDirectInput8WImpl_Initialize,
801     IDirectInput8WImpl_FindDevice,
802     IDirectInput8WImpl_EnumDevicesBySemantics,
803     IDirectInput8WImpl_ConfigureDevices
804 };
805
806 /*******************************************************************************
807  * DirectInput ClassFactory
808  */
809 typedef struct
810 {
811     /* IUnknown fields */
812     IClassFactory IClassFactory_iface;
813     LONG          ref;
814 } IClassFactoryImpl;
815
816 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
817 {
818         return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
819 }
820
821 static HRESULT WINAPI DICF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
822         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
823
824         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
825         return E_NOINTERFACE;
826 }
827
828 static ULONG WINAPI DICF_AddRef(LPCLASSFACTORY iface) {
829         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
830         return InterlockedIncrement(&(This->ref));
831 }
832
833 static ULONG WINAPI DICF_Release(LPCLASSFACTORY iface) {
834         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
835         /* static class, won't be  freed */
836         return InterlockedDecrement(&(This->ref));
837 }
838
839 static HRESULT WINAPI DICF_CreateInstance(
840         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
841 ) {
842         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
843
844         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
845         if ( IsEqualGUID( &IID_IUnknown, riid ) ||
846              IsEqualGUID( &IID_IDirectInputA, riid ) ||
847              IsEqualGUID( &IID_IDirectInputW, riid ) ||
848              IsEqualGUID( &IID_IDirectInput2A, riid ) ||
849              IsEqualGUID( &IID_IDirectInput2W, riid ) ||
850              IsEqualGUID( &IID_IDirectInput7A, riid ) ||
851              IsEqualGUID( &IID_IDirectInput7W, riid ) ||
852              IsEqualGUID( &IID_IDirectInput8A, riid ) ||
853              IsEqualGUID( &IID_IDirectInput8W, riid ) ) {
854                 /* FIXME: reuse already created dinput if present? */
855                 return DirectInputCreateEx(0,0,riid,ppobj,pOuter);
856         }
857
858         FIXME("(%p,%p,%s,%p) Interface not found!\n",This,pOuter,debugstr_guid(riid),ppobj);    
859         return E_NOINTERFACE;
860 }
861
862 static HRESULT WINAPI DICF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
863         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
864         FIXME("(%p)->(%d),stub!\n",This,dolock);
865         return S_OK;
866 }
867
868 static const IClassFactoryVtbl DICF_Vtbl = {
869         DICF_QueryInterface,
870         DICF_AddRef,
871         DICF_Release,
872         DICF_CreateInstance,
873         DICF_LockServer
874 };
875 static IClassFactoryImpl DINPUT_CF = {{&DICF_Vtbl}, 1 };
876
877 /***********************************************************************
878  *              DllCanUnloadNow (DINPUT.@)
879  */
880 HRESULT WINAPI DllCanUnloadNow(void)
881 {
882     return S_FALSE;
883 }
884
885 /***********************************************************************
886  *              DllGetClassObject (DINPUT.@)
887  */
888 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
889 {
890     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
891     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
892         *ppv = &DINPUT_CF;
893         IClassFactory_AddRef((IClassFactory*)*ppv);
894     return S_OK;
895     }
896
897     FIXME("(%s,%s,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
898     return CLASS_E_CLASSNOTAVAILABLE;
899 }
900
901 /***********************************************************************
902  *              DllRegisterServer (DINPUT.@)
903  */
904 HRESULT WINAPI DllRegisterServer(void)
905 {
906     return __wine_register_resources( DINPUT_instance, NULL );
907 }
908
909 /***********************************************************************
910  *              DllUnregisterServer (DINPUT.@)
911  */
912 HRESULT WINAPI DllUnregisterServer(void)
913 {
914     return __wine_unregister_resources( DINPUT_instance, NULL );
915 }
916
917 /******************************************************************************
918  *      DInput hook thread
919  */
920
921 static LRESULT CALLBACK LL_hook_proc( int code, WPARAM wparam, LPARAM lparam )
922 {
923     IDirectInputImpl *dinput;
924     int skip = 0;
925
926     if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );
927
928     EnterCriticalSection( &dinput_hook_crit );
929     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
930     {
931         IDirectInputDeviceImpl *dev;
932
933         EnterCriticalSection( &dinput->crit );
934         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
935             if (dev->acquired && dev->event_proc)
936             {
937                 TRACE("calling %p->%p (%lx %lx)\n", dev, dev->event_proc, wparam, lparam);
938                 skip |= dev->event_proc( &dev->IDirectInputDevice8A_iface, wparam, lparam );
939             }
940         LeaveCriticalSection( &dinput->crit );
941     }
942     LeaveCriticalSection( &dinput_hook_crit );
943
944     return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
945 }
946
947 static LRESULT CALLBACK callwndproc_proc( int code, WPARAM wparam, LPARAM lparam )
948 {
949     CWPSTRUCT *msg = (CWPSTRUCT *)lparam;
950     IDirectInputImpl *dinput;
951     HWND foreground;
952
953     if (code != HC_ACTION || (msg->message != WM_KILLFOCUS &&
954         msg->message != WM_ACTIVATEAPP && msg->message != WM_ACTIVATE))
955         return CallNextHookEx( 0, code, wparam, lparam );
956
957     foreground = GetForegroundWindow();
958
959     EnterCriticalSection( &dinput_hook_crit );
960
961     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
962     {
963         IDirectInputDeviceImpl *dev;
964
965         EnterCriticalSection( &dinput->crit );
966         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
967         {
968             if (!dev->acquired) continue;
969
970             if (msg->hwnd == dev->win && msg->hwnd != foreground)
971             {
972                 TRACE( "%p window is not foreground - unacquiring %p\n", dev->win, dev );
973                 IDirectInputDevice_Unacquire( &dev->IDirectInputDevice8A_iface );
974             }
975         }
976         LeaveCriticalSection( &dinput->crit );
977     }
978     LeaveCriticalSection( &dinput_hook_crit );
979
980     return CallNextHookEx( 0, code, wparam, lparam );
981 }
982
983 static DWORD WINAPI hook_thread_proc(void *param)
984 {
985     static HHOOK kbd_hook, mouse_hook;
986     MSG msg;
987
988     /* Force creation of the message queue */
989     PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE );
990     SetEvent(*(LPHANDLE)param);
991
992     while (GetMessageW( &msg, 0, 0, 0 ))
993     {
994         UINT kbd_cnt = 0, mice_cnt = 0;
995
996         if (msg.message == WM_USER+0x10)
997         {
998             IDirectInputImpl *dinput;
999
1000             TRACE( "Processing hook change notification lp:%ld\n", msg.lParam );
1001
1002             if (!msg.wParam && !msg.lParam)
1003             {
1004                 if (kbd_hook) UnhookWindowsHookEx( kbd_hook );
1005                 if (mouse_hook) UnhookWindowsHookEx( mouse_hook );
1006                 kbd_hook = mouse_hook = NULL;
1007                 break;
1008             }
1009
1010             EnterCriticalSection( &dinput_hook_crit );
1011
1012             /* Count acquired keyboards and mice*/
1013             LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1014             {
1015                 IDirectInputDeviceImpl *dev;
1016
1017                 EnterCriticalSection( &dinput->crit );
1018                 LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1019                 {
1020                     if (!dev->acquired || !dev->event_proc) continue;
1021
1022                     if (IsEqualGUID( &dev->guid, &GUID_SysKeyboard ) ||
1023                         IsEqualGUID( &dev->guid, &DInput_Wine_Keyboard_GUID ))
1024                         kbd_cnt++;
1025                     else
1026                         if (IsEqualGUID( &dev->guid, &GUID_SysMouse ) ||
1027                             IsEqualGUID( &dev->guid, &DInput_Wine_Mouse_GUID ))
1028                             mice_cnt++;
1029                 }
1030                 LeaveCriticalSection( &dinput->crit );
1031             }
1032             LeaveCriticalSection( &dinput_hook_crit );
1033
1034             if (kbd_cnt && !kbd_hook)
1035                 kbd_hook = SetWindowsHookExW( WH_KEYBOARD_LL, LL_hook_proc, DINPUT_instance, 0 );
1036             else if (!kbd_cnt && kbd_hook)
1037             {
1038                 UnhookWindowsHookEx( kbd_hook );
1039                 kbd_hook = NULL;
1040             }
1041
1042             if (mice_cnt && !mouse_hook)
1043                 mouse_hook = SetWindowsHookExW( WH_MOUSE_LL, LL_hook_proc, DINPUT_instance, 0 );
1044             else if (!mice_cnt && mouse_hook)
1045             {
1046                 UnhookWindowsHookEx( mouse_hook );
1047                 mouse_hook = NULL;
1048             }
1049         }
1050         TranslateMessage(&msg);
1051         DispatchMessageW(&msg);
1052     }
1053
1054     return 0;
1055 }
1056
1057 static DWORD hook_thread_id;
1058
1059 static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
1060 {
1061     0, 0, &dinput_hook_crit,
1062     { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
1063       0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
1064 };
1065 static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };
1066
1067 static BOOL check_hook_thread(void)
1068 {
1069     static HANDLE hook_thread;
1070
1071     EnterCriticalSection(&dinput_hook_crit);
1072
1073     TRACE("IDirectInputs left: %d\n", list_count(&direct_input_list));
1074     if (!list_empty(&direct_input_list) && !hook_thread)
1075     {
1076         HANDLE event;
1077
1078         event = CreateEventW(NULL, FALSE, FALSE, NULL);
1079         hook_thread = CreateThread(NULL, 0, hook_thread_proc, &event, 0, &hook_thread_id);
1080         if (event && hook_thread)
1081         {
1082             HANDLE handles[2];
1083             handles[0] = event;
1084             handles[1] = hook_thread;
1085             WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1086         }
1087         LeaveCriticalSection(&dinput_hook_crit);
1088         CloseHandle(event);
1089     }
1090     else if (list_empty(&direct_input_list) && hook_thread)
1091     {
1092         DWORD tid = hook_thread_id;
1093
1094         hook_thread_id = 0;
1095         PostThreadMessageW(tid, WM_USER+0x10, 0, 0);
1096         LeaveCriticalSection(&dinput_hook_crit);
1097
1098         /* wait for hook thread to exit */
1099         WaitForSingleObject(hook_thread, INFINITE);
1100         CloseHandle(hook_thread);
1101         hook_thread = NULL;
1102     }
1103     else
1104         LeaveCriticalSection(&dinput_hook_crit);
1105
1106     return hook_thread_id != 0;
1107 }
1108
1109 void check_dinput_hooks(LPDIRECTINPUTDEVICE8W iface)
1110 {
1111     static HHOOK callwndproc_hook;
1112     static ULONG foreground_cnt;
1113     IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8W(iface);
1114
1115     EnterCriticalSection(&dinput_hook_crit);
1116
1117     if (dev->dwCoopLevel & DISCL_FOREGROUND)
1118     {
1119         if (dev->acquired)
1120             foreground_cnt++;
1121         else
1122             foreground_cnt--;
1123     }
1124
1125     if (foreground_cnt && !callwndproc_hook)
1126         callwndproc_hook = SetWindowsHookExW( WH_CALLWNDPROC, callwndproc_proc,
1127                                               DINPUT_instance, GetCurrentThreadId() );
1128     else if (!foreground_cnt && callwndproc_hook)
1129     {
1130         UnhookWindowsHookEx( callwndproc_hook );
1131         callwndproc_hook = NULL;
1132     }
1133
1134     PostThreadMessageW( hook_thread_id, WM_USER+0x10, 1, 0 );
1135
1136     LeaveCriticalSection(&dinput_hook_crit);
1137 }