gdiplus: Implement GetDC for metafiles.
[wine] / dlls / dinput / dinput_main.c
1 /*              DirectInput
2  *
3  * Copyright 1998 Marcus Meissner
4  * Copyright 1998,1999 Lionel Ulmer
5  * Copyright 2000-2002 TransGaming Technologies Inc.
6  * Copyright 2007 Vitaliy Margolen
7  *
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22  */
23 /* Status:
24  *
25  * - Tomb Raider 2 Demo:
26  *   Playable using keyboard only.
27  * - WingCommander Prophecy Demo:
28  *   Doesn't get Input Focus.
29  *
30  * - Fallout : works great in X and DGA mode
31  */
32
33 #include "config.h"
34 #include <assert.h>
35 #include <stdarg.h>
36 #include <string.h>
37
38 #define COBJMACROS
39 #define NONAMELESSUNION
40
41 #include "wine/debug.h"
42 #include "wine/unicode.h"
43 #include "windef.h"
44 #include "winbase.h"
45 #include "winuser.h"
46 #include "winerror.h"
47 #include "objbase.h"
48 #include "rpcproxy.h"
49 #include "dinput_private.h"
50 #include "device_private.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(dinput);
53
54 static const IDirectInput7AVtbl ddi7avt;
55 static const IDirectInput7WVtbl ddi7wvt;
56 static const IDirectInput8AVtbl ddi8avt;
57 static const IDirectInput8WVtbl ddi8wvt;
58
59 static inline IDirectInputImpl *impl_from_IDirectInput7A( IDirectInput7A *iface )
60 {
61     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput7A_iface );
62 }
63
64 static inline IDirectInputImpl *impl_from_IDirectInput7W( IDirectInput7W *iface )
65 {
66     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput7W_iface );
67 }
68
69 static inline IDirectInputImpl *impl_from_IDirectInput8A( IDirectInput8A *iface )
70 {
71     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput8A_iface );
72 }
73
74 static inline IDirectInputImpl *impl_from_IDirectInput8W( IDirectInput8W *iface )
75 {
76     return CONTAINING_RECORD( iface, IDirectInputImpl, IDirectInput8W_iface );
77 }
78
79 static inline IDirectInputDeviceImpl *impl_from_IDirectInputDevice8A(IDirectInputDevice8A *iface)
80 {
81     return CONTAINING_RECORD(iface, IDirectInputDeviceImpl, IDirectInputDevice8A_iface);
82 }
83 static inline IDirectInputDeviceImpl *impl_from_IDirectInputDevice8W(IDirectInputDevice8W *iface)
84 {
85     return CONTAINING_RECORD(iface, IDirectInputDeviceImpl, IDirectInputDevice8W_iface);
86 }
87
88 static const struct dinput_device *dinput_devices[] =
89 {
90     &mouse_device,
91     &keyboard_device,
92     &joystick_linuxinput_device,
93     &joystick_linux_device,
94     &joystick_osx_device
95 };
96 #define NB_DINPUT_DEVICES (sizeof(dinput_devices)/sizeof(dinput_devices[0]))
97
98 static HINSTANCE DINPUT_instance = NULL;
99
100 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserv)
101 {
102     switch(reason)
103     {
104       case DLL_PROCESS_ATTACH:
105         DisableThreadLibraryCalls(inst);
106         DINPUT_instance = inst;
107         break;
108       case DLL_PROCESS_DETACH:
109         break;
110     }
111     return TRUE;
112 }
113
114 static BOOL check_hook_thread(void);
115 static CRITICAL_SECTION dinput_hook_crit;
116 static struct list direct_input_list = LIST_INIT( direct_input_list );
117
118 static HRESULT initialize_directinput_instance(IDirectInputImpl *This, DWORD dwVersion);
119 static void uninitialize_directinput_instance(IDirectInputImpl *This);
120
121 static HRESULT create_directinput_instance(REFIID riid, LPVOID *ppDI, IDirectInputImpl **out)
122 {
123     IDirectInputImpl *This = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(IDirectInputImpl) );
124     HRESULT hr;
125
126     if (!This)
127         return E_OUTOFMEMORY;
128
129     This->IDirectInput7A_iface.lpVtbl = &ddi7avt;
130     This->IDirectInput7W_iface.lpVtbl = &ddi7wvt;
131     This->IDirectInput8A_iface.lpVtbl = &ddi8avt;
132     This->IDirectInput8W_iface.lpVtbl = &ddi8wvt;
133
134     hr = IDirectInput_QueryInterface( &This->IDirectInput7A_iface, riid, ppDI );
135     if (FAILED(hr))
136     {
137         HeapFree( GetProcessHeap(), 0, This );
138         return hr;
139     }
140
141     if (out) *out = This;
142     return DI_OK;
143 }
144
145 /******************************************************************************
146  *      DirectInputCreateEx (DINPUT.@)
147  */
148 HRESULT WINAPI DirectInputCreateEx(
149         HINSTANCE hinst, DWORD dwVersion, REFIID riid, LPVOID *ppDI,
150         LPUNKNOWN punkOuter)
151 {
152     IDirectInputImpl *This;
153     HRESULT hr;
154
155     TRACE("(%p,%04x,%s,%p,%p)\n", hinst, dwVersion, debugstr_guid(riid), ppDI, punkOuter);
156
157     if (IsEqualGUID( &IID_IDirectInputA,  riid ) ||
158         IsEqualGUID( &IID_IDirectInput2A, riid ) ||
159         IsEqualGUID( &IID_IDirectInput7A, riid ) ||
160         IsEqualGUID( &IID_IDirectInputW,  riid ) ||
161         IsEqualGUID( &IID_IDirectInput2W, riid ) ||
162         IsEqualGUID( &IID_IDirectInput7W, riid ))
163     {
164         hr = create_directinput_instance(riid, ppDI, &This);
165         if (FAILED(hr))
166             return hr;
167     }
168     else
169         return DIERR_NOINTERFACE;
170
171     hr = IDirectInput_Initialize( &This->IDirectInput7A_iface, hinst, dwVersion );
172     if (FAILED(hr))
173     {
174         IDirectInput_Release( &This->IDirectInput7A_iface );
175         *ppDI = NULL;
176         return hr;
177     }
178
179     return DI_OK;
180 }
181
182 /******************************************************************************
183  *      DirectInputCreateA (DINPUT.@)
184  */
185 HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateA(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA *ppDI, LPUNKNOWN punkOuter)
186 {
187     return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7A, (LPVOID *)ppDI, punkOuter);
188 }
189
190 /******************************************************************************
191  *      DirectInputCreateW (DINPUT.@)
192  */
193 HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateW(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTW *ppDI, LPUNKNOWN punkOuter)
194 {
195     return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7W, (LPVOID *)ppDI, punkOuter);
196 }
197
198 static const char *_dump_DIDEVTYPE_value(DWORD dwDevType) {
199     switch (dwDevType) {
200         case 0: return "All devices";
201         case DIDEVTYPE_MOUSE: return "DIDEVTYPE_MOUSE";
202         case DIDEVTYPE_KEYBOARD: return "DIDEVTYPE_KEYBOARD";
203         case DIDEVTYPE_JOYSTICK: return "DIDEVTYPE_JOYSTICK";
204         case DIDEVTYPE_DEVICE: return "DIDEVTYPE_DEVICE";
205         default: return "Unknown";
206     }
207 }
208
209 static void _dump_EnumDevices_dwFlags(DWORD dwFlags) {
210     if (TRACE_ON(dinput)) {
211         unsigned int   i;
212         static const struct {
213             DWORD       mask;
214             const char  *name;
215         } flags[] = {
216 #define FE(x) { x, #x}
217             FE(DIEDFL_ALLDEVICES),
218             FE(DIEDFL_ATTACHEDONLY),
219             FE(DIEDFL_FORCEFEEDBACK),
220             FE(DIEDFL_INCLUDEALIASES),
221             FE(DIEDFL_INCLUDEPHANTOMS)
222 #undef FE
223         };
224         TRACE(" flags: ");
225         if (dwFlags == 0) {
226             TRACE("DIEDFL_ALLDEVICES\n");
227             return;
228         }
229         for (i = 0; i < (sizeof(flags) / sizeof(flags[0])); i++)
230             if (flags[i].mask & dwFlags)
231                 TRACE("%s ",flags[i].name);
232     }
233     TRACE("\n");
234 }
235
236 void _dump_diactionformatA(LPDIACTIONFORMATA lpdiActionFormat) {
237     unsigned int i;
238
239     FIXME("diaf.dwSize = %d\n", lpdiActionFormat->dwSize);
240     FIXME("diaf.dwActionSize = %d\n", lpdiActionFormat->dwActionSize);
241     FIXME("diaf.dwDataSize = %d\n", lpdiActionFormat->dwDataSize);
242     FIXME("diaf.dwNumActions = %d\n", lpdiActionFormat->dwNumActions);
243     FIXME("diaf.rgoAction = %p\n", lpdiActionFormat->rgoAction);
244     FIXME("diaf.guidActionMap = %s\n", debugstr_guid(&lpdiActionFormat->guidActionMap));
245     FIXME("diaf.dwGenre = 0x%08x\n", lpdiActionFormat->dwGenre);
246     FIXME("diaf.dwBufferSize = %d\n", lpdiActionFormat->dwBufferSize);
247     FIXME("diaf.lAxisMin = %d\n", lpdiActionFormat->lAxisMin);
248     FIXME("diaf.lAxisMax = %d\n", lpdiActionFormat->lAxisMax);
249     FIXME("diaf.hInstString = %p\n", lpdiActionFormat->hInstString);
250     FIXME("diaf.ftTimeStamp ...\n");
251     FIXME("diaf.dwCRC = 0x%x\n", lpdiActionFormat->dwCRC);
252     FIXME("diaf.tszActionMap = %s\n", debugstr_a(lpdiActionFormat->tszActionMap));
253     for (i = 0; i < lpdiActionFormat->dwNumActions; i++)
254     {
255         FIXME("diaf.rgoAction[%u]:\n", i);
256         FIXME("\tuAppData=0x%lx\n", lpdiActionFormat->rgoAction[i].uAppData);
257         FIXME("\tdwSemantic=0x%08x\n", lpdiActionFormat->rgoAction[i].dwSemantic);
258         FIXME("\tdwFlags=0x%x\n", lpdiActionFormat->rgoAction[i].dwFlags);
259         FIXME("\tszActionName=%s\n", debugstr_a(lpdiActionFormat->rgoAction[i].u.lptszActionName));
260         FIXME("\tguidInstance=%s\n", debugstr_guid(&lpdiActionFormat->rgoAction[i].guidInstance));
261         FIXME("\tdwObjID=0x%x\n", lpdiActionFormat->rgoAction[i].dwObjID);
262         FIXME("\tdwHow=0x%x\n", lpdiActionFormat->rgoAction[i].dwHow);
263     }
264 }
265
266 void _copy_diactionformatAtoW(LPDIACTIONFORMATW to, LPDIACTIONFORMATA from)
267 {
268     int i;
269
270     to->dwSize = sizeof(DIACTIONFORMATW);
271     to->dwActionSize = sizeof(DIACTIONW);
272     to->dwDataSize = from->dwDataSize;
273     to->dwNumActions = from->dwNumActions;
274     to->guidActionMap = from->guidActionMap;
275     to->dwGenre = from->dwGenre;
276     to->dwBufferSize = from->dwBufferSize;
277     to->lAxisMin = from->lAxisMin;
278     to->lAxisMax = from->lAxisMax;
279     to->dwCRC = from->dwCRC;
280     to->ftTimeStamp = from->ftTimeStamp;
281
282     for (i=0; i < to->dwNumActions; i++)
283     {
284         to->rgoAction[i].uAppData = from->rgoAction[i].uAppData;
285         to->rgoAction[i].dwSemantic = from->rgoAction[i].dwSemantic;
286         to->rgoAction[i].dwFlags = from->rgoAction[i].dwFlags;
287         to->rgoAction[i].guidInstance = from->rgoAction[i].guidInstance;
288         to->rgoAction[i].dwObjID = from->rgoAction[i].dwObjID;
289         to->rgoAction[i].dwHow = from->rgoAction[i].dwHow;
290     }
291 }
292
293 void _copy_diactionformatWtoA(LPDIACTIONFORMATA to, LPDIACTIONFORMATW from)
294 {
295     int i;
296
297     to->dwSize = sizeof(DIACTIONFORMATA);
298     to->dwActionSize = sizeof(DIACTIONA);
299     to->dwDataSize = from->dwDataSize;
300     to->dwNumActions = from->dwNumActions;
301     to->guidActionMap = from->guidActionMap;
302     to->dwGenre = from->dwGenre;
303     to->dwBufferSize = from->dwBufferSize;
304     to->lAxisMin = from->lAxisMin;
305     to->lAxisMax = from->lAxisMax;
306     to->dwCRC = from->dwCRC;
307     to->ftTimeStamp = from->ftTimeStamp;
308
309     for (i=0; i < to->dwNumActions; i++)
310     {
311         to->rgoAction[i].uAppData = from->rgoAction[i].uAppData;
312         to->rgoAction[i].dwSemantic = from->rgoAction[i].dwSemantic;
313         to->rgoAction[i].dwFlags = from->rgoAction[i].dwFlags;
314         to->rgoAction[i].guidInstance = from->rgoAction[i].guidInstance;
315         to->rgoAction[i].dwObjID = from->rgoAction[i].dwObjID;
316         to->rgoAction[i].dwHow = from->rgoAction[i].dwHow;
317     }
318 }
319
320 /******************************************************************************
321  *      IDirectInputA_EnumDevices
322  */
323 static HRESULT WINAPI IDirectInputAImpl_EnumDevices(
324         LPDIRECTINPUT7A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
325         LPVOID pvRef, DWORD dwFlags)
326 {
327     IDirectInputImpl *This = impl_from_IDirectInput7A(iface);
328     DIDEVICEINSTANCEA devInstance;
329     unsigned int i;
330     int j, r;
331
332     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
333           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
334           lpCallback, pvRef, dwFlags);
335     _dump_EnumDevices_dwFlags(dwFlags);
336
337     if (!lpCallback)
338         return DIERR_INVALIDPARAM;
339
340     if (!This->initialized)
341         return DIERR_NOTINITIALIZED;
342
343     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
344         if (!dinput_devices[i]->enum_deviceA) continue;
345         for (j = 0, r = -1; r != 0; j++) {
346             devInstance.dwSize = sizeof(devInstance);
347             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
348             if ((r = dinput_devices[i]->enum_deviceA(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
349                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
350                     return 0;
351             }
352         }
353     }
354     
355     return 0;
356 }
357 /******************************************************************************
358  *      IDirectInputW_EnumDevices
359  */
360 static HRESULT WINAPI IDirectInputWImpl_EnumDevices(
361         LPDIRECTINPUT7W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
362         LPVOID pvRef, DWORD dwFlags) 
363 {
364     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
365     DIDEVICEINSTANCEW devInstance;
366     unsigned int i;
367     int j, r;
368
369     TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
370           This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
371           lpCallback, pvRef, dwFlags);
372     _dump_EnumDevices_dwFlags(dwFlags);
373
374     if (!lpCallback)
375         return DIERR_INVALIDPARAM;
376
377     if (!This->initialized)
378         return DIERR_NOTINITIALIZED;
379
380     for (i = 0; i < NB_DINPUT_DEVICES; i++) {
381         if (!dinput_devices[i]->enum_deviceW) continue;
382         for (j = 0, r = -1; r != 0; j++) {
383             devInstance.dwSize = sizeof(devInstance);
384             TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
385             if ((r = dinput_devices[i]->enum_deviceW(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
386                 if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
387                     return 0;
388             }
389         }
390     }
391     
392     return 0;
393 }
394
395 static ULONG WINAPI IDirectInputAImpl_AddRef(LPDIRECTINPUT7A iface)
396 {
397     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
398     ULONG ref = InterlockedIncrement(&This->ref);
399
400     TRACE( "(%p) incrementing from %d\n", This, ref - 1);
401     return ref;
402 }
403
404 static ULONG WINAPI IDirectInputWImpl_AddRef(LPDIRECTINPUT7W iface)
405 {
406     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
407     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
408 }
409
410 static ULONG WINAPI IDirectInputAImpl_Release(LPDIRECTINPUT7A iface)
411 {
412     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
413     ULONG ref = InterlockedDecrement( &This->ref );
414
415     TRACE( "(%p) releasing from %d\n", This, ref + 1 );
416
417     if (ref == 0)
418     {
419         uninitialize_directinput_instance( This );
420         HeapFree( GetProcessHeap(), 0, This );
421     }
422
423     return ref;
424 }
425
426 static ULONG WINAPI IDirectInputWImpl_Release(LPDIRECTINPUT7W iface)
427 {
428     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
429     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
430 }
431
432 static HRESULT WINAPI IDirectInputAImpl_QueryInterface(LPDIRECTINPUT7A iface, REFIID riid, LPVOID *ppobj)
433 {
434     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
435
436     TRACE( "(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppobj );
437
438     if (!riid || !ppobj)
439         return E_POINTER;
440
441     if (IsEqualGUID( &IID_IUnknown, riid ) ||
442         IsEqualGUID( &IID_IDirectInputA,  riid ) ||
443         IsEqualGUID( &IID_IDirectInput2A, riid ) ||
444         IsEqualGUID( &IID_IDirectInput7A, riid ))
445     {
446         *ppobj = &This->IDirectInput7A_iface;
447         IUnknown_AddRef( (IUnknown*)*ppobj );
448
449         return DI_OK;
450     }
451
452     if (IsEqualGUID( &IID_IDirectInputW,  riid ) ||
453         IsEqualGUID( &IID_IDirectInput2W, riid ) ||
454         IsEqualGUID( &IID_IDirectInput7W, riid ))
455     {
456         *ppobj = &This->IDirectInput7W_iface;
457         IUnknown_AddRef( (IUnknown*)*ppobj );
458
459         return DI_OK;
460     }
461
462     if (IsEqualGUID( &IID_IDirectInput8A, riid ))
463     {
464         *ppobj = &This->IDirectInput8A_iface;
465         IUnknown_AddRef( (IUnknown*)*ppobj );
466
467         return DI_OK;
468     }
469
470     if (IsEqualGUID( &IID_IDirectInput8W, riid ))
471     {
472         *ppobj = &This->IDirectInput8W_iface;
473         IUnknown_AddRef( (IUnknown*)*ppobj );
474
475         return DI_OK;
476     }
477
478     FIXME( "Unsupported interface: %s\n", debugstr_guid(riid));
479     *ppobj = NULL;
480     return E_NOINTERFACE;
481 }
482
483 static HRESULT WINAPI IDirectInputWImpl_QueryInterface(LPDIRECTINPUT7W iface, REFIID riid, LPVOID *ppobj)
484 {
485     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
486     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
487 }
488
489 static HRESULT initialize_directinput_instance(IDirectInputImpl *This, DWORD dwVersion)
490 {
491     if (!This->initialized)
492     {
493         This->dwVersion = dwVersion;
494         This->evsequence = 1;
495
496         InitializeCriticalSection( &This->crit );
497         This->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": IDirectInputImpl*->crit");
498
499         list_init( &This->devices_list );
500
501         /* Add self to the list of the IDirectInputs */
502         EnterCriticalSection( &dinput_hook_crit );
503         list_add_head( &direct_input_list, &This->entry );
504         LeaveCriticalSection( &dinput_hook_crit );
505
506         This->initialized = TRUE;
507
508         if (!check_hook_thread())
509         {
510             uninitialize_directinput_instance( This );
511             return DIERR_GENERIC;
512         }
513     }
514
515     return DI_OK;
516 }
517
518 static void uninitialize_directinput_instance(IDirectInputImpl *This)
519 {
520     if (This->initialized)
521     {
522         /* Remove self from the list of the IDirectInputs */
523         EnterCriticalSection( &dinput_hook_crit );
524         list_remove( &This->entry );
525         LeaveCriticalSection( &dinput_hook_crit );
526
527         check_hook_thread();
528
529         This->crit.DebugInfo->Spare[0] = 0;
530         DeleteCriticalSection( &This->crit );
531
532         This->initialized = FALSE;
533     }
534 }
535
536 enum directinput_versions
537 {
538     DIRECTINPUT_VERSION_300 = 0x0300,
539     DIRECTINPUT_VERSION_500 = 0x0500,
540     DIRECTINPUT_VERSION_50A = 0x050A,
541     DIRECTINPUT_VERSION_5B2 = 0x05B2,
542     DIRECTINPUT_VERSION_602 = 0x0602,
543     DIRECTINPUT_VERSION_61A = 0x061A,
544     DIRECTINPUT_VERSION_700 = 0x0700,
545 };
546
547 static HRESULT WINAPI IDirectInputAImpl_Initialize(LPDIRECTINPUT7A iface, HINSTANCE hinst, DWORD version)
548 {
549     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
550
551     TRACE("(%p)->(%p, 0x%04x)\n", iface, hinst, version);
552
553     if (!hinst)
554         return DIERR_INVALIDPARAM;
555     else if (version == 0)
556         return DIERR_NOTINITIALIZED;
557     else if (version > DIRECTINPUT_VERSION_700)
558         return DIERR_OLDDIRECTINPUTVERSION;
559     else if (version != DIRECTINPUT_VERSION_300 && version != DIRECTINPUT_VERSION_500 &&
560              version != DIRECTINPUT_VERSION_50A && version != DIRECTINPUT_VERSION_5B2 &&
561              version != DIRECTINPUT_VERSION_602 && version != DIRECTINPUT_VERSION_61A &&
562              version != DIRECTINPUT_VERSION_700 && version != DIRECTINPUT_VERSION)
563         return DIERR_BETADIRECTINPUTVERSION;
564
565     return initialize_directinput_instance(This, version);
566 }
567
568 static HRESULT WINAPI IDirectInputWImpl_Initialize(LPDIRECTINPUT7W iface, HINSTANCE hinst, DWORD x)
569 {
570     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
571     return IDirectInputAImpl_Initialize( &This->IDirectInput7A_iface, hinst, x );
572 }
573
574 static HRESULT WINAPI IDirectInputAImpl_GetDeviceStatus(LPDIRECTINPUT7A iface, REFGUID rguid)
575 {
576     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
577     HRESULT hr;
578     LPDIRECTINPUTDEVICEA device;
579
580     TRACE( "(%p)->(%s)\n", This, debugstr_guid(rguid) );
581
582     if (!This->initialized)
583         return DIERR_NOTINITIALIZED;
584
585     hr = IDirectInput_CreateDevice( iface, rguid, &device, NULL );
586     if (hr != DI_OK) return DI_NOTATTACHED;
587
588     IUnknown_Release( device );
589
590     return DI_OK;
591 }
592
593 static HRESULT WINAPI IDirectInputWImpl_GetDeviceStatus(LPDIRECTINPUT7W iface, REFGUID rguid)
594 {
595     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
596     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
597 }
598
599 static HRESULT WINAPI IDirectInputAImpl_RunControlPanel(LPDIRECTINPUT7A iface,
600                                                         HWND hwndOwner,
601                                                         DWORD dwFlags)
602 {
603     WCHAR control_exeW[] = {'c','o','n','t','r','o','l','.','e','x','e',0};
604     STARTUPINFOW si = {0};
605     PROCESS_INFORMATION pi;
606
607     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
608
609     TRACE( "(%p)->(%p, %08x)\n", This, hwndOwner, dwFlags );
610
611     if (hwndOwner && !IsWindow(hwndOwner))
612         return E_HANDLE;
613
614     if (dwFlags)
615         return DIERR_INVALIDPARAM;
616
617     if (!This->initialized)
618         return DIERR_NOTINITIALIZED;
619
620     if (!CreateProcessW(NULL, control_exeW, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi))
621         return HRESULT_FROM_WIN32(GetLastError());
622
623     return DI_OK;
624 }
625
626 static HRESULT WINAPI IDirectInputWImpl_RunControlPanel(LPDIRECTINPUT7W iface, HWND hwndOwner, DWORD dwFlags)
627 {
628     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
629     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
630 }
631
632 static HRESULT WINAPI IDirectInput2AImpl_FindDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
633                                                     LPCSTR pszName, LPGUID pguidInstance)
634 {
635     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
636
637     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), pszName, pguidInstance );
638
639     return DI_OK;
640 }
641
642 static HRESULT WINAPI IDirectInput2WImpl_FindDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
643                                                     LPCWSTR pszName, LPGUID pguidInstance)
644 {
645     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
646
647     FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), debugstr_w(pszName), pguidInstance );
648
649     return DI_OK;
650 }
651
652 static HRESULT create_device(IDirectInputImpl *This, REFGUID rguid, REFIID riid, LPVOID *pvOut, BOOL unicode)
653 {
654     unsigned int i;
655
656     if (pvOut)
657         *pvOut = NULL;
658
659     if (!rguid || !pvOut)
660         return E_POINTER;
661
662     if (!This->initialized)
663         return DIERR_NOTINITIALIZED;
664
665     /* Loop on all the devices to see if anyone matches the given GUID */
666     for (i = 0; i < NB_DINPUT_DEVICES; i++)
667     {
668         HRESULT ret;
669
670         if (!dinput_devices[i]->create_device) continue;
671         if ((ret = dinput_devices[i]->create_device(This, rguid, riid, pvOut, unicode)) == DI_OK)
672             return DI_OK;
673     }
674
675     WARN("invalid device GUID %s\n", debugstr_guid(rguid));
676     return DIERR_DEVICENOTREG;
677 }
678
679 static HRESULT WINAPI IDirectInput7AImpl_CreateDeviceEx(LPDIRECTINPUT7A iface, REFGUID rguid,
680                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
681 {
682     IDirectInputImpl *This = impl_from_IDirectInput7A( iface );
683
684     TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
685
686     return create_device(This, rguid, riid, pvOut, FALSE);
687 }
688
689 static HRESULT WINAPI IDirectInput7WImpl_CreateDeviceEx(LPDIRECTINPUT7W iface, REFGUID rguid,
690                                                         REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
691 {
692     IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
693
694     TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);
695
696     return create_device(This, rguid, riid, pvOut, TRUE);
697 }
698
699 static HRESULT WINAPI IDirectInputAImpl_CreateDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
700                                                      LPDIRECTINPUTDEVICEA* pdev, LPUNKNOWN punk)
701 {
702     return IDirectInput7AImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
703 }
704
705 static HRESULT WINAPI IDirectInputWImpl_CreateDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
706                                                      LPDIRECTINPUTDEVICEW* pdev, LPUNKNOWN punk)
707 {
708     return IDirectInput7WImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
709 }
710
711 /*******************************************************************************
712  *      DirectInput8
713  */
714
715 static ULONG WINAPI IDirectInput8AImpl_AddRef(LPDIRECTINPUT8A iface)
716 {
717     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
718     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
719 }
720
721 static ULONG WINAPI IDirectInput8WImpl_AddRef(LPDIRECTINPUT8W iface)
722 {
723     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
724     return IDirectInputAImpl_AddRef( &This->IDirectInput7A_iface );
725 }
726
727 static HRESULT WINAPI IDirectInput8AImpl_QueryInterface(LPDIRECTINPUT8A iface, REFIID riid, LPVOID *ppobj)
728 {
729     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
730     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
731 }
732
733 static HRESULT WINAPI IDirectInput8WImpl_QueryInterface(LPDIRECTINPUT8W iface, REFIID riid, LPVOID *ppobj)
734 {
735     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
736     return IDirectInputAImpl_QueryInterface( &This->IDirectInput7A_iface, riid, ppobj );
737 }
738
739 static ULONG WINAPI IDirectInput8AImpl_Release(LPDIRECTINPUT8A iface)
740 {
741     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
742     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
743 }
744
745 static ULONG WINAPI IDirectInput8WImpl_Release(LPDIRECTINPUT8W iface)
746 {
747     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
748     return IDirectInputAImpl_Release( &This->IDirectInput7A_iface );
749 }
750
751 static HRESULT WINAPI IDirectInput8AImpl_CreateDevice(LPDIRECTINPUT8A iface, REFGUID rguid,
752                                                       LPDIRECTINPUTDEVICE8A* pdev, LPUNKNOWN punk)
753 {
754     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
755     return IDirectInput7AImpl_CreateDeviceEx( &This->IDirectInput7A_iface, rguid, NULL, (LPVOID*)pdev, punk );
756 }
757
758 static HRESULT WINAPI IDirectInput8WImpl_CreateDevice(LPDIRECTINPUT8W iface, REFGUID rguid,
759                                                       LPDIRECTINPUTDEVICE8W* pdev, LPUNKNOWN punk)
760 {
761     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
762     return IDirectInput7WImpl_CreateDeviceEx( &This->IDirectInput7W_iface, rguid, NULL, (LPVOID*)pdev, punk );
763 }
764
765 static HRESULT WINAPI IDirectInput8AImpl_EnumDevices(LPDIRECTINPUT8A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
766                                                      LPVOID pvRef, DWORD dwFlags)
767 {
768     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
769     return IDirectInputAImpl_EnumDevices( &This->IDirectInput7A_iface, dwDevType, lpCallback, pvRef, dwFlags );
770 }
771
772 static HRESULT WINAPI IDirectInput8WImpl_EnumDevices(LPDIRECTINPUT8W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
773                                                      LPVOID pvRef, DWORD dwFlags)
774 {
775     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
776     return IDirectInputWImpl_EnumDevices( &This->IDirectInput7W_iface, dwDevType, lpCallback, pvRef, dwFlags );
777 }
778
779 static HRESULT WINAPI IDirectInput8AImpl_GetDeviceStatus(LPDIRECTINPUT8A iface, REFGUID rguid)
780 {
781     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
782     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
783 }
784
785 static HRESULT WINAPI IDirectInput8WImpl_GetDeviceStatus(LPDIRECTINPUT8W iface, REFGUID rguid)
786 {
787     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
788     return IDirectInputAImpl_GetDeviceStatus( &This->IDirectInput7A_iface, rguid );
789 }
790
791 static HRESULT WINAPI IDirectInput8AImpl_RunControlPanel(LPDIRECTINPUT8A iface, HWND hwndOwner, DWORD dwFlags)
792 {
793     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
794     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
795 }
796
797 static HRESULT WINAPI IDirectInput8WImpl_RunControlPanel(LPDIRECTINPUT8W iface, HWND hwndOwner, DWORD dwFlags)
798 {
799     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
800     return IDirectInputAImpl_RunControlPanel( &This->IDirectInput7A_iface, hwndOwner, dwFlags );
801 }
802
803 static HRESULT WINAPI IDirectInput8AImpl_Initialize(LPDIRECTINPUT8A iface, HINSTANCE hinst, DWORD version)
804 {
805     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
806
807     TRACE("(%p)->(%p, 0x%04x)\n", iface, hinst, version);
808
809     if (!hinst)
810         return DIERR_INVALIDPARAM;
811     else if (version == 0)
812         return DIERR_NOTINITIALIZED;
813     else if (version < DIRECTINPUT_VERSION)
814         return DIERR_BETADIRECTINPUTVERSION;
815     else if (version > DIRECTINPUT_VERSION)
816         return DIERR_OLDDIRECTINPUTVERSION;
817
818     return initialize_directinput_instance(This, version);
819 }
820
821 static HRESULT WINAPI IDirectInput8WImpl_Initialize(LPDIRECTINPUT8W iface, HINSTANCE hinst, DWORD version)
822 {
823     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
824     return IDirectInput8AImpl_Initialize( &This->IDirectInput8A_iface, hinst, version );
825 }
826
827 static HRESULT WINAPI IDirectInput8AImpl_FindDevice(LPDIRECTINPUT8A iface, REFGUID rguid, LPCSTR pszName, LPGUID pguidInstance)
828 {
829     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
830     return IDirectInput2AImpl_FindDevice( &This->IDirectInput7A_iface, rguid, pszName, pguidInstance );
831 }
832
833 static HRESULT WINAPI IDirectInput8WImpl_FindDevice(LPDIRECTINPUT8W iface, REFGUID rguid, LPCWSTR pszName, LPGUID pguidInstance)
834 {
835     IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
836     return IDirectInput2WImpl_FindDevice( &This->IDirectInput7W_iface, rguid, pszName, pguidInstance );
837 }
838
839 static HRESULT WINAPI IDirectInput8AImpl_EnumDevicesBySemantics(
840       LPDIRECTINPUT8A iface, LPCSTR ptszUserName, LPDIACTIONFORMATA lpdiActionFormat,
841       LPDIENUMDEVICESBYSEMANTICSCBA lpCallback,
842       LPVOID pvRef, DWORD dwFlags
843 )
844 {
845     IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
846     DIDEVICEINSTANCEA didevi;
847     LPDIRECTINPUTDEVICE8A lpdid;
848     BOOL ret;
849     DWORD callbackFlags = 0;
850     int i;
851
852     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, ptszUserName, lpdiActionFormat,
853           lpCallback, pvRef, dwFlags);
854 #define X(x) if (dwFlags & x) FIXME("\tdwFlags |= "#x"\n");
855         X(DIEDBSFL_ATTACHEDONLY)
856         X(DIEDBSFL_THISUSER)
857         X(DIEDBSFL_FORCEFEEDBACK)
858         X(DIEDBSFL_AVAILABLEDEVICES)
859         X(DIEDBSFL_MULTIMICEKEYBOARDS)
860         X(DIEDBSFL_NONGAMINGDEVICES)
861 #undef X
862
863     _dump_diactionformatA(lpdiActionFormat);
864
865     didevi.dwSize = sizeof(didevi);
866
867     /* enum the keyboard first */
868     IDirectInput_CreateDevice(iface, &GUID_SysKeyboard, &lpdid, NULL);
869     IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
870     /* if there's any DIKEYBOARD action, keyboard is priority 1*/
871     for(i=0; i < lpdiActionFormat->dwActionSize; i++)
872         if ((lpdiActionFormat->rgoAction[i].dwSemantic & DIKEYBOARD_MASK) == DIKEYBOARD_MASK)
873             callbackFlags |= DIEDBS_MAPPEDPRI1;
874
875     ret = lpCallback(&didevi, lpdid, callbackFlags, 1, pvRef);
876
877     if (ret == DIENUM_STOP) return DI_OK;
878
879     callbackFlags = 0;
880
881     /* and then the mouse */
882     IDirectInput_CreateDevice(iface, &GUID_SysMouse, &lpdid, NULL);
883     IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
884     /* same as above, but for the mouse */
885     for(i=0; i < lpdiActionFormat->dwActionSize; i++)
886         if ((lpdiActionFormat->rgoAction[i].dwSemantic & DIMOUSE_MASK) == DIMOUSE_MASK)
887             callbackFlags |= DIEDBS_MAPPEDPRI1;
888
889     lpCallback(&didevi, lpdid, callbackFlags, 0, pvRef);
890
891     return DI_OK;
892 }
893
894 static HRESULT WINAPI IDirectInput8WImpl_EnumDevicesBySemantics(
895       LPDIRECTINPUT8W iface, LPCWSTR ptszUserName, LPDIACTIONFORMATW lpdiActionFormat,
896       LPDIENUMDEVICESBYSEMANTICSCBW lpCallback,
897       LPVOID pvRef, DWORD dwFlags
898 )
899 {
900     IDirectInputImpl *This = impl_from_IDirectInput8W(iface);
901     DIDEVICEINSTANCEW didevi;
902     LPDIRECTINPUTDEVICE8W lpdid;
903     BOOL ret;
904     DWORD callbackFlags = 0;
905     int i;
906
907     FIXME("(this=%p,%s,%p,%p,%p,%04x): semi-stub\n", This, debugstr_w(ptszUserName), lpdiActionFormat,
908           lpCallback, pvRef, dwFlags);
909
910     didevi.dwSize = sizeof(didevi);
911
912     /* enum the keyboard first */
913     IDirectInput_CreateDevice(iface, &GUID_SysKeyboard, &lpdid, NULL);
914     IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
915     /* if there's any DIKEYBOARD action, keyboard is priority 1*/
916     for(i=0; i < lpdiActionFormat->dwActionSize; i++)
917         if ((lpdiActionFormat->rgoAction[i].dwSemantic & DIKEYBOARD_MASK) == DIKEYBOARD_MASK)
918             callbackFlags |= DIEDBS_MAPPEDPRI1;
919
920     ret = lpCallback(&didevi, lpdid, callbackFlags, 1, pvRef);
921
922     if (ret == DIENUM_STOP) return DI_OK;
923
924     callbackFlags = 0;
925
926     /* and then the mouse */
927     IDirectInput_CreateDevice(iface, &GUID_SysMouse, &lpdid, NULL);
928     IDirectInputDevice_GetDeviceInfo(lpdid, &didevi);
929     /* same as above, but for the mouse */
930     for(i=0; i < lpdiActionFormat->dwActionSize; i++)
931         if ((lpdiActionFormat->rgoAction[i].dwSemantic & DIMOUSE_MASK) == DIMOUSE_MASK)
932             callbackFlags |= DIEDBS_MAPPEDPRI1;
933
934     lpCallback(&didevi, lpdid, callbackFlags, 0, pvRef);
935
936     return DI_OK;
937 }
938
939 static HRESULT WINAPI IDirectInput8AImpl_ConfigureDevices(
940       LPDIRECTINPUT8A iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
941       LPDICONFIGUREDEVICESPARAMSA lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
942 )
943 {
944       IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
945
946       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
947             dwFlags, pvRefData);
948       return 0;
949 }
950
951 static HRESULT WINAPI IDirectInput8WImpl_ConfigureDevices(
952       LPDIRECTINPUT8W iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
953       LPDICONFIGUREDEVICESPARAMSW lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
954 )
955 {
956       IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
957
958       FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
959             dwFlags, pvRefData);
960       return 0;
961 }
962
963 static const IDirectInput7AVtbl ddi7avt = {
964     IDirectInputAImpl_QueryInterface,
965     IDirectInputAImpl_AddRef,
966     IDirectInputAImpl_Release,
967     IDirectInputAImpl_CreateDevice,
968     IDirectInputAImpl_EnumDevices,
969     IDirectInputAImpl_GetDeviceStatus,
970     IDirectInputAImpl_RunControlPanel,
971     IDirectInputAImpl_Initialize,
972     IDirectInput2AImpl_FindDevice,
973     IDirectInput7AImpl_CreateDeviceEx
974 };
975
976 static const IDirectInput7WVtbl ddi7wvt = {
977     IDirectInputWImpl_QueryInterface,
978     IDirectInputWImpl_AddRef,
979     IDirectInputWImpl_Release,
980     IDirectInputWImpl_CreateDevice,
981     IDirectInputWImpl_EnumDevices,
982     IDirectInputWImpl_GetDeviceStatus,
983     IDirectInputWImpl_RunControlPanel,
984     IDirectInputWImpl_Initialize,
985     IDirectInput2WImpl_FindDevice,
986     IDirectInput7WImpl_CreateDeviceEx
987 };
988
989 static const IDirectInput8AVtbl ddi8avt = {
990     IDirectInput8AImpl_QueryInterface,
991     IDirectInput8AImpl_AddRef,
992     IDirectInput8AImpl_Release,
993     IDirectInput8AImpl_CreateDevice,
994     IDirectInput8AImpl_EnumDevices,
995     IDirectInput8AImpl_GetDeviceStatus,
996     IDirectInput8AImpl_RunControlPanel,
997     IDirectInput8AImpl_Initialize,
998     IDirectInput8AImpl_FindDevice,
999     IDirectInput8AImpl_EnumDevicesBySemantics,
1000     IDirectInput8AImpl_ConfigureDevices
1001 };
1002
1003 static const IDirectInput8WVtbl ddi8wvt = {
1004     IDirectInput8WImpl_QueryInterface,
1005     IDirectInput8WImpl_AddRef,
1006     IDirectInput8WImpl_Release,
1007     IDirectInput8WImpl_CreateDevice,
1008     IDirectInput8WImpl_EnumDevices,
1009     IDirectInput8WImpl_GetDeviceStatus,
1010     IDirectInput8WImpl_RunControlPanel,
1011     IDirectInput8WImpl_Initialize,
1012     IDirectInput8WImpl_FindDevice,
1013     IDirectInput8WImpl_EnumDevicesBySemantics,
1014     IDirectInput8WImpl_ConfigureDevices
1015 };
1016
1017 /*******************************************************************************
1018  * DirectInput ClassFactory
1019  */
1020 typedef struct
1021 {
1022     /* IUnknown fields */
1023     IClassFactory IClassFactory_iface;
1024     LONG          ref;
1025 } IClassFactoryImpl;
1026
1027 static inline IClassFactoryImpl *impl_from_IClassFactory(IClassFactory *iface)
1028 {
1029         return CONTAINING_RECORD(iface, IClassFactoryImpl, IClassFactory_iface);
1030 }
1031
1032 static HRESULT WINAPI DICF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
1033         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1034
1035         FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
1036         return E_NOINTERFACE;
1037 }
1038
1039 static ULONG WINAPI DICF_AddRef(LPCLASSFACTORY iface) {
1040         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1041         return InterlockedIncrement(&(This->ref));
1042 }
1043
1044 static ULONG WINAPI DICF_Release(LPCLASSFACTORY iface) {
1045         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1046         /* static class, won't be  freed */
1047         return InterlockedDecrement(&(This->ref));
1048 }
1049
1050 static HRESULT WINAPI DICF_CreateInstance(
1051         LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
1052 ) {
1053         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1054
1055         TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
1056         if ( IsEqualGUID( &IID_IUnknown, riid ) ||
1057              IsEqualGUID( &IID_IDirectInputA, riid ) ||
1058              IsEqualGUID( &IID_IDirectInputW, riid ) ||
1059              IsEqualGUID( &IID_IDirectInput2A, riid ) ||
1060              IsEqualGUID( &IID_IDirectInput2W, riid ) ||
1061              IsEqualGUID( &IID_IDirectInput7A, riid ) ||
1062              IsEqualGUID( &IID_IDirectInput7W, riid ) ) {
1063                 return create_directinput_instance(riid, ppobj, NULL);
1064         }
1065
1066         FIXME("(%p,%p,%s,%p) Interface not found!\n",This,pOuter,debugstr_guid(riid),ppobj);    
1067         return E_NOINTERFACE;
1068 }
1069
1070 static HRESULT WINAPI DICF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
1071         IClassFactoryImpl *This = impl_from_IClassFactory(iface);
1072         FIXME("(%p)->(%d),stub!\n",This,dolock);
1073         return S_OK;
1074 }
1075
1076 static const IClassFactoryVtbl DICF_Vtbl = {
1077         DICF_QueryInterface,
1078         DICF_AddRef,
1079         DICF_Release,
1080         DICF_CreateInstance,
1081         DICF_LockServer
1082 };
1083 static IClassFactoryImpl DINPUT_CF = {{&DICF_Vtbl}, 1 };
1084
1085 /***********************************************************************
1086  *              DllCanUnloadNow (DINPUT.@)
1087  */
1088 HRESULT WINAPI DllCanUnloadNow(void)
1089 {
1090     return S_FALSE;
1091 }
1092
1093 /***********************************************************************
1094  *              DllGetClassObject (DINPUT.@)
1095  */
1096 HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
1097 {
1098     TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1099     if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
1100         *ppv = &DINPUT_CF;
1101         IClassFactory_AddRef((IClassFactory*)*ppv);
1102     return S_OK;
1103     }
1104
1105     FIXME("(%s,%s,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
1106     return CLASS_E_CLASSNOTAVAILABLE;
1107 }
1108
1109 /***********************************************************************
1110  *              DllRegisterServer (DINPUT.@)
1111  */
1112 HRESULT WINAPI DllRegisterServer(void)
1113 {
1114     return __wine_register_resources( DINPUT_instance, NULL );
1115 }
1116
1117 /***********************************************************************
1118  *              DllUnregisterServer (DINPUT.@)
1119  */
1120 HRESULT WINAPI DllUnregisterServer(void)
1121 {
1122     return __wine_unregister_resources( DINPUT_instance, NULL );
1123 }
1124
1125 /******************************************************************************
1126  *      DInput hook thread
1127  */
1128
1129 static LRESULT CALLBACK LL_hook_proc( int code, WPARAM wparam, LPARAM lparam )
1130 {
1131     IDirectInputImpl *dinput;
1132     int skip = 0;
1133
1134     if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );
1135
1136     EnterCriticalSection( &dinput_hook_crit );
1137     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1138     {
1139         IDirectInputDeviceImpl *dev;
1140
1141         EnterCriticalSection( &dinput->crit );
1142         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1143             if (dev->acquired && dev->event_proc)
1144             {
1145                 TRACE("calling %p->%p (%lx %lx)\n", dev, dev->event_proc, wparam, lparam);
1146                 skip |= dev->event_proc( &dev->IDirectInputDevice8A_iface, wparam, lparam );
1147             }
1148         LeaveCriticalSection( &dinput->crit );
1149     }
1150     LeaveCriticalSection( &dinput_hook_crit );
1151
1152     return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
1153 }
1154
1155 static LRESULT CALLBACK callwndproc_proc( int code, WPARAM wparam, LPARAM lparam )
1156 {
1157     CWPSTRUCT *msg = (CWPSTRUCT *)lparam;
1158     IDirectInputImpl *dinput;
1159     HWND foreground;
1160
1161     if (code != HC_ACTION || (msg->message != WM_KILLFOCUS &&
1162         msg->message != WM_ACTIVATEAPP && msg->message != WM_ACTIVATE))
1163         return CallNextHookEx( 0, code, wparam, lparam );
1164
1165     foreground = GetForegroundWindow();
1166
1167     EnterCriticalSection( &dinput_hook_crit );
1168
1169     LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1170     {
1171         IDirectInputDeviceImpl *dev;
1172
1173         EnterCriticalSection( &dinput->crit );
1174         LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1175         {
1176             if (!dev->acquired) continue;
1177
1178             if (msg->hwnd == dev->win && msg->hwnd != foreground)
1179             {
1180                 TRACE( "%p window is not foreground - unacquiring %p\n", dev->win, dev );
1181                 IDirectInputDevice_Unacquire( &dev->IDirectInputDevice8A_iface );
1182             }
1183         }
1184         LeaveCriticalSection( &dinput->crit );
1185     }
1186     LeaveCriticalSection( &dinput_hook_crit );
1187
1188     return CallNextHookEx( 0, code, wparam, lparam );
1189 }
1190
1191 static DWORD WINAPI hook_thread_proc(void *param)
1192 {
1193     static HHOOK kbd_hook, mouse_hook;
1194     MSG msg;
1195
1196     /* Force creation of the message queue */
1197     PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE );
1198     SetEvent(*(LPHANDLE)param);
1199
1200     while (GetMessageW( &msg, 0, 0, 0 ))
1201     {
1202         UINT kbd_cnt = 0, mice_cnt = 0;
1203
1204         if (msg.message == WM_USER+0x10)
1205         {
1206             IDirectInputImpl *dinput;
1207
1208             TRACE( "Processing hook change notification lp:%ld\n", msg.lParam );
1209
1210             if (!msg.wParam && !msg.lParam)
1211             {
1212                 if (kbd_hook) UnhookWindowsHookEx( kbd_hook );
1213                 if (mouse_hook) UnhookWindowsHookEx( mouse_hook );
1214                 kbd_hook = mouse_hook = NULL;
1215                 break;
1216             }
1217
1218             EnterCriticalSection( &dinput_hook_crit );
1219
1220             /* Count acquired keyboards and mice*/
1221             LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
1222             {
1223                 IDirectInputDeviceImpl *dev;
1224
1225                 EnterCriticalSection( &dinput->crit );
1226                 LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDeviceImpl, entry )
1227                 {
1228                     if (!dev->acquired || !dev->event_proc) continue;
1229
1230                     if (IsEqualGUID( &dev->guid, &GUID_SysKeyboard ) ||
1231                         IsEqualGUID( &dev->guid, &DInput_Wine_Keyboard_GUID ))
1232                         kbd_cnt++;
1233                     else
1234                         if (IsEqualGUID( &dev->guid, &GUID_SysMouse ) ||
1235                             IsEqualGUID( &dev->guid, &DInput_Wine_Mouse_GUID ))
1236                             mice_cnt++;
1237                 }
1238                 LeaveCriticalSection( &dinput->crit );
1239             }
1240             LeaveCriticalSection( &dinput_hook_crit );
1241
1242             if (kbd_cnt && !kbd_hook)
1243                 kbd_hook = SetWindowsHookExW( WH_KEYBOARD_LL, LL_hook_proc, DINPUT_instance, 0 );
1244             else if (!kbd_cnt && kbd_hook)
1245             {
1246                 UnhookWindowsHookEx( kbd_hook );
1247                 kbd_hook = NULL;
1248             }
1249
1250             if (mice_cnt && !mouse_hook)
1251                 mouse_hook = SetWindowsHookExW( WH_MOUSE_LL, LL_hook_proc, DINPUT_instance, 0 );
1252             else if (!mice_cnt && mouse_hook)
1253             {
1254                 UnhookWindowsHookEx( mouse_hook );
1255                 mouse_hook = NULL;
1256             }
1257         }
1258         TranslateMessage(&msg);
1259         DispatchMessageW(&msg);
1260     }
1261
1262     return 0;
1263 }
1264
1265 static DWORD hook_thread_id;
1266
1267 static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
1268 {
1269     0, 0, &dinput_hook_crit,
1270     { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
1271       0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
1272 };
1273 static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };
1274
1275 static BOOL check_hook_thread(void)
1276 {
1277     static HANDLE hook_thread;
1278
1279     EnterCriticalSection(&dinput_hook_crit);
1280
1281     TRACE("IDirectInputs left: %d\n", list_count(&direct_input_list));
1282     if (!list_empty(&direct_input_list) && !hook_thread)
1283     {
1284         HANDLE event;
1285
1286         event = CreateEventW(NULL, FALSE, FALSE, NULL);
1287         hook_thread = CreateThread(NULL, 0, hook_thread_proc, &event, 0, &hook_thread_id);
1288         if (event && hook_thread)
1289         {
1290             HANDLE handles[2];
1291             handles[0] = event;
1292             handles[1] = hook_thread;
1293             WaitForMultipleObjects(2, handles, FALSE, INFINITE);
1294         }
1295         LeaveCriticalSection(&dinput_hook_crit);
1296         CloseHandle(event);
1297     }
1298     else if (list_empty(&direct_input_list) && hook_thread)
1299     {
1300         DWORD tid = hook_thread_id;
1301
1302         hook_thread_id = 0;
1303         PostThreadMessageW(tid, WM_USER+0x10, 0, 0);
1304         LeaveCriticalSection(&dinput_hook_crit);
1305
1306         /* wait for hook thread to exit */
1307         WaitForSingleObject(hook_thread, INFINITE);
1308         CloseHandle(hook_thread);
1309         hook_thread = NULL;
1310     }
1311     else
1312         LeaveCriticalSection(&dinput_hook_crit);
1313
1314     return hook_thread_id != 0;
1315 }
1316
1317 void check_dinput_hooks(LPDIRECTINPUTDEVICE8W iface)
1318 {
1319     static HHOOK callwndproc_hook;
1320     static ULONG foreground_cnt;
1321     IDirectInputDeviceImpl *dev = impl_from_IDirectInputDevice8W(iface);
1322
1323     EnterCriticalSection(&dinput_hook_crit);
1324
1325     if (dev->dwCoopLevel & DISCL_FOREGROUND)
1326     {
1327         if (dev->acquired)
1328             foreground_cnt++;
1329         else
1330             foreground_cnt--;
1331     }
1332
1333     if (foreground_cnt && !callwndproc_hook)
1334         callwndproc_hook = SetWindowsHookExW( WH_CALLWNDPROC, callwndproc_proc,
1335                                               DINPUT_instance, GetCurrentThreadId() );
1336     else if (!foreground_cnt && callwndproc_hook)
1337     {
1338         UnhookWindowsHookEx( callwndproc_hook );
1339         callwndproc_hook = NULL;
1340     }
1341
1342     PostThreadMessageW( hook_thread_id, WM_USER+0x10, 1, 0 );
1343
1344     LeaveCriticalSection(&dinput_hook_crit);
1345 }