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