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