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