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