dinput_main.c 36.4 KB
Newer Older
Alexandre Julliard's avatar
Alexandre Julliard committed
1 2 3
/*		DirectInput
 *
 * 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 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
Alexandre Julliard's avatar
Alexandre Julliard committed
22 23 24 25
 */
/* Status:
 *
 * - Tomb Raider 2 Demo:
Alexandre Julliard's avatar
Alexandre Julliard committed
26
 *   Playable using keyboard only.
Alexandre Julliard's avatar
Alexandre Julliard committed
27
 * - WingCommander Prophecy Demo:
Alexandre Julliard's avatar
Alexandre Julliard committed
28
 *   Doesn't get Input Focus.
29
 *
30
 * - Fallout : works great in X and DGA mode
Alexandre Julliard's avatar
Alexandre Julliard committed
31 32 33 34
 */

#include "config.h"
#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"
Lionel Ulmer's avatar
Lionel Ulmer committed
47
#include "dinput_private.h"
48
#include "device_private.h"
49

50
WINE_DEFAULT_DEBUG_CHANNEL(dinput);
51

52 53 54 55
static const IDirectInput7AVtbl ddi7avt;
static const IDirectInput7WVtbl ddi7wvt;
static const IDirectInput8AVtbl ddi8avt;
static const IDirectInput8WVtbl ddi8wvt;
56

57 58
static inline IDirectInputImpl *impl_from_IDirectInput7W( IDirectInput7W *iface )
{
59
    return CONTAINING_RECORD( iface, IDirectInputImpl, lpVtbl7w );
60 61 62 63
}

static inline IDirectInputImpl *impl_from_IDirectInput8A( IDirectInput8A *iface )
{
64
    return CONTAINING_RECORD( iface, IDirectInputImpl, lpVtbl8a );
65 66 67 68
}

static inline IDirectInputImpl *impl_from_IDirectInput8W( IDirectInput8W *iface )
{
69
    return CONTAINING_RECORD( iface, IDirectInputImpl, lpVtbl8w );
70 71 72 73 74 75 76
}

static inline IDirectInput7W *IDirectInput7W_from_impl( IDirectInputImpl *iface )
{
    return (IDirectInput7W *)(&iface->lpVtbl7w);
}

77 78 79 80 81
static const struct dinput_device *dinput_devices[] =
{
    &mouse_device,
    &keyboard_device,
    &joystick_linuxinput_device,
82 83
    &joystick_linux_device,
    &joystick_osx_device
84 85
};
#define NB_DINPUT_DEVICES (sizeof(dinput_devices)/sizeof(dinput_devices[0]))
86

87
static HINSTANCE DINPUT_instance = NULL;
88

89
BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserv)
90 91 92 93
{
    switch(reason)
    {
      case DLL_PROCESS_ATTACH:
94
        DisableThreadLibraryCalls(inst);
95
        DINPUT_instance = inst;
96 97 98 99 100 101 102
        break;
      case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

103 104 105
static BOOL check_hook_thread(void);
static CRITICAL_SECTION dinput_hook_crit;
static struct list direct_input_list = LIST_INIT( direct_input_list );
106

107
/******************************************************************************
108
 *	DirectInputCreateEx (DINPUT.@)
109 110 111
 */
HRESULT WINAPI DirectInputCreateEx(
	HINSTANCE hinst, DWORD dwVersion, REFIID riid, LPVOID *ppDI,
112 113
	LPUNKNOWN punkOuter) 
{
114 115
    IDirectInputImpl* This;

116
    TRACE("(%p,%04x,%s,%p,%p)\n", hinst, dwVersion, debugstr_guid(riid), ppDI, punkOuter);
117

118 119
    if (IsEqualGUID( &IID_IUnknown,       riid ) ||
        IsEqualGUID( &IID_IDirectInputA,  riid ) ||
120 121 122 123 124 125 126 127 128 129 130
        IsEqualGUID( &IID_IDirectInput2A, riid ) ||
        IsEqualGUID( &IID_IDirectInput7A, riid ) ||
        IsEqualGUID( &IID_IDirectInputW,  riid ) ||
        IsEqualGUID( &IID_IDirectInput2W, riid ) ||
        IsEqualGUID( &IID_IDirectInput7W, riid ) ||
        IsEqualGUID( &IID_IDirectInput8A, riid ) ||
        IsEqualGUID( &IID_IDirectInput8W, riid ))
    {
        if (!(This = HeapAlloc( GetProcessHeap(), 0, sizeof(IDirectInputImpl) )))
            return DIERR_OUTOFMEMORY;
    }
131 132
    else
        return DIERR_OLDDIRECTINPUTVERSION;
133

134 135 136 137 138
    This->lpVtbl      = &ddi7avt;
    This->lpVtbl7w    = &ddi7wvt;
    This->lpVtbl8a    = &ddi8avt;
    This->lpVtbl8w    = &ddi8wvt;
    This->ref         = 0;
139 140
    This->dwVersion   = dwVersion;
    This->evsequence  = 1;
141

142 143
    InitializeCriticalSection(&This->crit);
    This->crit.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": IDirectInputImpl*->crit");
144

145
    list_init( &This->devices_list );
146

147 148 149 150 151 152 153 154 155
    /* Add self to the list of the IDirectInputs */
    EnterCriticalSection( &dinput_hook_crit );
    list_add_head( &direct_input_list, &This->entry );
    LeaveCriticalSection( &dinput_hook_crit );

    if (!check_hook_thread())
    {
        IUnknown_Release( (LPDIRECTINPUT7A)This );
        return DIERR_GENERIC;
156
    }
157

158
    IDirectInput_QueryInterface( (IDirectInput7A *)This, riid, ppDI );
159
    return DI_OK;
160 161
}

Alexandre Julliard's avatar
Alexandre Julliard committed
162
/******************************************************************************
163
 *	DirectInputCreateA (DINPUT.@)
Alexandre Julliard's avatar
Alexandre Julliard committed
164
 */
165
HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateA(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA *ppDI, LPUNKNOWN punkOuter)
166
{
167
    return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7A, (LPVOID *)ppDI, punkOuter);
168 169 170 171 172
}

/******************************************************************************
 *	DirectInputCreateW (DINPUT.@)
 */
173
HRESULT WINAPI DECLSPEC_HOTPATCH DirectInputCreateW(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTW *ppDI, LPUNKNOWN punkOuter)
174
{
175
    return DirectInputCreateEx(hinst, dwVersion, &IID_IDirectInput7W, (LPVOID *)ppDI, punkOuter);
176
}
177

178
static const char *_dump_DIDEVTYPE_value(DWORD dwDevType) {
179 180 181 182 183 184
    switch (dwDevType) {
        case 0: return "All devices";
	case DIDEVTYPE_MOUSE: return "DIDEVTYPE_MOUSE";
	case DIDEVTYPE_KEYBOARD: return "DIDEVTYPE_KEYBOARD";
	case DIDEVTYPE_JOYSTICK: return "DIDEVTYPE_JOYSTICK";
	case DIDEVTYPE_DEVICE: return "DIDEVTYPE_DEVICE";
185
	default: return "Unknown";
186 187 188 189 190
    }
}

static void _dump_EnumDevices_dwFlags(DWORD dwFlags) {
    if (TRACE_ON(dinput)) {
191
	unsigned int   i;
192 193 194 195 196 197 198 199 200 201 202 203
	static const struct {
	    DWORD       mask;
	    const char  *name;
	} flags[] = {
#define FE(x) { x, #x}
	    FE(DIEDFL_ALLDEVICES),
	    FE(DIEDFL_ATTACHEDONLY),
	    FE(DIEDFL_FORCEFEEDBACK),
	    FE(DIEDFL_INCLUDEALIASES),
	    FE(DIEDFL_INCLUDEPHANTOMS)
#undef FE
	};
204
	TRACE(" flags: ");
205
	if (dwFlags == 0) {
206
	    TRACE("DIEDFL_ALLDEVICES\n");
207 208 209 210
	    return;
	}
	for (i = 0; i < (sizeof(flags) / sizeof(flags[0])); i++)
	    if (flags[i].mask & dwFlags)
Andrew Riedi's avatar
Andrew Riedi committed
211
		TRACE("%s ",flags[i].name);
212
    }
213
    TRACE("\n");
Alexandre Julliard's avatar
Alexandre Julliard committed
214
}
215

216
void _dump_diactionformatA(LPDIACTIONFORMATA lpdiActionFormat) {
217
    unsigned int i;
218 219 220 221 222 223 224

    FIXME("diaf.dwSize = %d\n", lpdiActionFormat->dwSize);
    FIXME("diaf.dwActionSize = %d\n", lpdiActionFormat->dwActionSize);
    FIXME("diaf.dwDataSize = %d\n", lpdiActionFormat->dwDataSize);
    FIXME("diaf.dwNumActions = %d\n", lpdiActionFormat->dwNumActions);
    FIXME("diaf.rgoAction = %p\n", lpdiActionFormat->rgoAction);
    FIXME("diaf.guidActionMap = %s\n", debugstr_guid(&lpdiActionFormat->guidActionMap));
225
    FIXME("diaf.dwGenre = 0x%08x\n", lpdiActionFormat->dwGenre);
226 227 228 229 230
    FIXME("diaf.dwBufferSize = %d\n", lpdiActionFormat->dwBufferSize);
    FIXME("diaf.lAxisMin = %d\n", lpdiActionFormat->lAxisMin);
    FIXME("diaf.lAxisMax = %d\n", lpdiActionFormat->lAxisMax);
    FIXME("diaf.hInstString = %p\n", lpdiActionFormat->hInstString);
    FIXME("diaf.ftTimeStamp ...\n");
231
    FIXME("diaf.dwCRC = 0x%x\n", lpdiActionFormat->dwCRC);
232
    FIXME("diaf.tszActionMap = %s\n", debugstr_a(lpdiActionFormat->tszActionMap));
233 234 235 236 237 238 239 240 241 242 243
    for (i = 0; i < lpdiActionFormat->dwNumActions; i++)
    {
        FIXME("diaf.rgoAction[%u]:\n", i);
        FIXME("\tuAppData=0x%lx\n", lpdiActionFormat->rgoAction[i].uAppData);
        FIXME("\tdwSemantic=0x%08x\n", lpdiActionFormat->rgoAction[i].dwSemantic);
        FIXME("\tdwFlags=0x%x\n", lpdiActionFormat->rgoAction[i].dwFlags);
        FIXME("\tszActionName=%s\n", debugstr_a(lpdiActionFormat->rgoAction[i].u.lptszActionName));
        FIXME("\tguidInstance=%s\n", debugstr_guid(&lpdiActionFormat->rgoAction[i].guidInstance));
        FIXME("\tdwObjID=0x%x\n", lpdiActionFormat->rgoAction[i].dwObjID);
        FIXME("\tdwHow=0x%x\n", lpdiActionFormat->rgoAction[i].dwHow);
    }
244 245
}

Alexandre Julliard's avatar
Alexandre Julliard committed
246
/******************************************************************************
Alexandre Julliard's avatar
Alexandre Julliard committed
247
 *	IDirectInputA_EnumDevices
Alexandre Julliard's avatar
Alexandre Julliard committed
248
 */
249
static HRESULT WINAPI IDirectInputAImpl_EnumDevices(
250
	LPDIRECTINPUT7A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
251
	LPVOID pvRef, DWORD dwFlags)
252
{
253
    IDirectInputImpl *This = (IDirectInputImpl *)iface;
254
    DIDEVICEINSTANCEA devInstance;
255 256 257
    unsigned int i;
    int j, r;

258
    TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
259 260
	  This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
	  lpCallback, pvRef, dwFlags);
261
    _dump_EnumDevices_dwFlags(dwFlags);
262

263 264
    for (i = 0; i < NB_DINPUT_DEVICES; i++) {
        if (!dinput_devices[i]->enum_deviceA) continue;
265 266
        for (j = 0, r = -1; r != 0; j++) {
	    devInstance.dwSize = sizeof(devInstance);
267
	    TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
268
	    if ((r = dinput_devices[i]->enum_deviceA(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
269 270 271
	        if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
		    return 0;
	    }
272
	}
273 274 275
    }
    
    return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
276
}
277 278 279 280 281 282 283
/******************************************************************************
 *	IDirectInputW_EnumDevices
 */
static HRESULT WINAPI IDirectInputWImpl_EnumDevices(
	LPDIRECTINPUT7W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
	LPVOID pvRef, DWORD dwFlags) 
{
284
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
285
    DIDEVICEINSTANCEW devInstance;
286 287 288
    unsigned int i;
    int j, r;

289
    TRACE("(this=%p,0x%04x '%s',%p,%p,%04x)\n",
290 291
	  This, dwDevType, _dump_DIDEVTYPE_value(dwDevType),
	  lpCallback, pvRef, dwFlags);
292
    _dump_EnumDevices_dwFlags(dwFlags);
293

294 295
    for (i = 0; i < NB_DINPUT_DEVICES; i++) {
        if (!dinput_devices[i]->enum_deviceW) continue;
296 297
        for (j = 0, r = -1; r != 0; j++) {
	    devInstance.dwSize = sizeof(devInstance);
298
	    TRACE("  - checking device %u ('%s')\n", i, dinput_devices[i]->name);
299
	    if ((r = dinput_devices[i]->enum_deviceW(dwDevType, dwFlags, &devInstance, This->dwVersion, j))) {
300 301 302
	        if (lpCallback(&devInstance,pvRef) == DIENUM_STOP)
		    return 0;
	    }
303
	}
304 305 306
    }
    
    return 0;
307 308
}

309
static ULONG WINAPI IDirectInputAImpl_AddRef(LPDIRECTINPUT7A iface)
310
{
311 312 313 314 315 316 317 318 319 320 321
    IDirectInputImpl *This = (IDirectInputImpl *)iface;
    ULONG ref = InterlockedIncrement(&This->ref);

    TRACE( "(%p) incrementing from %d\n", This, ref - 1);
    return ref;
}

static ULONG WINAPI IDirectInputWImpl_AddRef(LPDIRECTINPUT7W iface)
{
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
    return IDirectInputAImpl_AddRef( (IDirectInput7A *)This );
Alexandre Julliard's avatar
Alexandre Julliard committed
322 323
}

324
static ULONG WINAPI IDirectInputAImpl_Release(LPDIRECTINPUT7A iface)
325
{
326
    IDirectInputImpl *This = (IDirectInputImpl *)iface;
327 328 329
    ULONG ref = InterlockedDecrement( &This->ref );

    TRACE( "(%p) releasing from %d\n", This, ref + 1 );
330 331 332

    if (ref) return ref;

333 334 335 336 337 338
    /* Remove self from the list of the IDirectInputs */
    EnterCriticalSection( &dinput_hook_crit );
    list_remove( &This->entry );
    LeaveCriticalSection( &dinput_hook_crit );

    check_hook_thread();
339 340 341 342 343 344

    This->crit.DebugInfo->Spare[0] = 0;
    DeleteCriticalSection( &This->crit );
    HeapFree( GetProcessHeap(), 0, This );

    return 0;
Alexandre Julliard's avatar
Alexandre Julliard committed
345 346
}

347 348 349 350
static ULONG WINAPI IDirectInputWImpl_Release(LPDIRECTINPUT7W iface)
{
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
    return IDirectInputAImpl_Release( (IDirectInput7A *)This );
351 352
}

353 354 355
static HRESULT WINAPI IDirectInputAImpl_QueryInterface(LPDIRECTINPUT7A iface, REFIID riid, LPVOID *ppobj)
{
    IDirectInputImpl *This = (IDirectInputImpl *)iface;
356

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    TRACE( "(%p)->(%s,%p)\n", This, debugstr_guid(riid), ppobj );

    if (IsEqualGUID( &IID_IUnknown, riid ) ||
        IsEqualGUID( &IID_IDirectInputA,  riid ) ||
        IsEqualGUID( &IID_IDirectInput2A, riid ) ||
        IsEqualGUID( &IID_IDirectInput7A, riid ))
    {
        *ppobj = &This->lpVtbl;
        IUnknown_AddRef( (IUnknown*)*ppobj );

        return DI_OK;
    }

    if (IsEqualGUID( &IID_IDirectInputW,  riid ) ||
        IsEqualGUID( &IID_IDirectInput2W, riid ) ||
        IsEqualGUID( &IID_IDirectInput7W, riid ))
    {
        *ppobj = &This->lpVtbl7w;
        IUnknown_AddRef( (IUnknown*)*ppobj );

        return DI_OK;
    }

    if (IsEqualGUID( &IID_IDirectInput8A, riid ))
    {
        *ppobj = &This->lpVtbl8a;
        IUnknown_AddRef( (IUnknown*)*ppobj );

        return DI_OK;
    }

    if (IsEqualGUID( &IID_IDirectInput8W, riid ))
    {
        *ppobj = &This->lpVtbl8w;
        IUnknown_AddRef( (IUnknown*)*ppobj );

        return DI_OK;
    }

396
    FIXME( "Unsupported interface: %s\n", debugstr_guid(riid));
397 398 399 400 401 402 403
    return E_FAIL;
}

static HRESULT WINAPI IDirectInputWImpl_QueryInterface(LPDIRECTINPUT7W iface, REFIID riid, LPVOID *ppobj)
{
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
    return IDirectInputAImpl_QueryInterface( (IDirectInput7A *)This, riid, ppobj );
404 405 406
}

static HRESULT WINAPI IDirectInputAImpl_Initialize(LPDIRECTINPUT7A iface, HINSTANCE hinst, DWORD x) {
407
	TRACE("(this=%p,%p,%x)\n",iface, hinst, x);
408 409 410 411 412 413
	
	/* Initialize can return: DIERR_BETADIRECTINPUTVERSION, DIERR_OLDDIRECTINPUTVERSION and DI_OK.
	 * Since we already initialized the device, return DI_OK. In the past we returned DIERR_ALREADYINITIALIZED
	 * which broke applications like Tomb Raider Legend because it isn't a legal return value.
	 */
	return DI_OK;
Alexandre Julliard's avatar
Alexandre Julliard committed
414 415
}

416 417 418 419 420 421 422 423 424
static HRESULT WINAPI IDirectInputWImpl_Initialize(LPDIRECTINPUT7W iface, HINSTANCE hinst, DWORD x)
{
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
    return IDirectInputAImpl_Initialize( (IDirectInput7A *)This, hinst, x );
}

static HRESULT WINAPI IDirectInputAImpl_GetDeviceStatus(LPDIRECTINPUT7A iface, REFGUID rguid)
{
    IDirectInputImpl *This = (IDirectInputImpl *)iface;
425 426
    HRESULT hr;
    LPDIRECTINPUTDEVICEA device;
427

428 429 430 431 432 433
    TRACE( "(%p)->(%s)\n", This, debugstr_guid(rguid) );

    hr = IDirectInput_CreateDevice( iface, rguid, &device, NULL );
    if (hr != DI_OK) return DI_NOTATTACHED;

    IUnknown_Release( device );
434

435 436
    return DI_OK;
}
437

438 439 440 441
static HRESULT WINAPI IDirectInputWImpl_GetDeviceStatus(LPDIRECTINPUT7W iface, REFGUID rguid)
{
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
    return IDirectInputAImpl_GetDeviceStatus( (IDirectInput7A *)This, rguid );
442 443
}

444
static HRESULT WINAPI IDirectInputAImpl_RunControlPanel(LPDIRECTINPUT7A iface,
445
							HWND hwndOwner,
446 447 448
							DWORD dwFlags)
{
    IDirectInputImpl *This = (IDirectInputImpl *)iface;
449

450 451 452 453 454 455 456 457 458
    FIXME( "(%p)->(%p,%08x): stub\n", This, hwndOwner, dwFlags );

    return DI_OK;
}

static HRESULT WINAPI IDirectInputWImpl_RunControlPanel(LPDIRECTINPUT7W iface, HWND hwndOwner, DWORD dwFlags)
{
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
    return IDirectInputAImpl_RunControlPanel( (IDirectInput7A *)This, hwndOwner, dwFlags );
459 460
}

461
static HRESULT WINAPI IDirectInput2AImpl_FindDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
462 463 464 465 466
						    LPCSTR pszName, LPGUID pguidInstance)
{
    IDirectInputImpl *This = (IDirectInputImpl *)iface;

    FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), pszName, pguidInstance );
467

468
    return DI_OK;
Lionel Ulmer's avatar
Lionel Ulmer committed
469 470
}

471
static HRESULT WINAPI IDirectInput2WImpl_FindDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
472 473 474 475 476
						    LPCWSTR pszName, LPGUID pguidInstance)
{
    IDirectInputImpl *This = impl_from_IDirectInput7W( iface );

    FIXME( "(%p)->(%s, %s, %p): stub\n", This, debugstr_guid(rguid), debugstr_w(pszName), pguidInstance );
477

478
    return DI_OK;
479 480
}

Lionel Ulmer's avatar
Lionel Ulmer committed
481 482 483
static HRESULT WINAPI IDirectInput7AImpl_CreateDeviceEx(LPDIRECTINPUT7A iface, REFGUID rguid,
							REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
{
484
  IDirectInputImpl *This = (IDirectInputImpl *)iface;
Lionel Ulmer's avatar
Lionel Ulmer committed
485
  HRESULT ret_value = DIERR_DEVICENOTREG;
486
  unsigned int i;
487

Lionel Ulmer's avatar
Lionel Ulmer committed
488 489
  TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);

490 491
  if (!rguid || !pvOut) return E_POINTER;

Lionel Ulmer's avatar
Lionel Ulmer committed
492
  /* Loop on all the devices to see if anyone matches the given GUID */
493
  for (i = 0; i < NB_DINPUT_DEVICES; i++) {
Lionel Ulmer's avatar
Lionel Ulmer committed
494
    HRESULT ret;
495

496
    if (!dinput_devices[i]->create_deviceA) continue;
497
    if ((ret = dinput_devices[i]->create_deviceA(This, rguid, riid, (LPDIRECTINPUTDEVICEA*) pvOut)) == DI_OK)
498 499 500 501
    {
      EnterCriticalSection( &This->crit );
      list_add_tail( &This->devices_list, &(*(IDirectInputDevice2AImpl**)pvOut)->entry );
      LeaveCriticalSection( &This->crit );
Lionel Ulmer's avatar
Lionel Ulmer committed
502
      return DI_OK;
503
    }
504

Lionel Ulmer's avatar
Lionel Ulmer committed
505 506 507
    if (ret == DIERR_NOINTERFACE)
      ret_value = DIERR_NOINTERFACE;
  }
508

509 510 511 512 513
  if (ret_value == DIERR_NOINTERFACE)
  {
    WARN("invalid device GUID %s\n", debugstr_guid(rguid));
  }

Lionel Ulmer's avatar
Lionel Ulmer committed
514 515 516
  return ret_value;
}

517 518 519
static HRESULT WINAPI IDirectInput7WImpl_CreateDeviceEx(LPDIRECTINPUT7W iface, REFGUID rguid,
							REFIID riid, LPVOID* pvOut, LPUNKNOWN lpUnknownOuter)
{
520
  IDirectInputImpl *This = impl_from_IDirectInput7W( iface );
521
  HRESULT ret_value = DIERR_DEVICENOTREG;
522
  unsigned int i;
523 524 525

  TRACE("(%p)->(%s, %s, %p, %p)\n", This, debugstr_guid(rguid), debugstr_guid(riid), pvOut, lpUnknownOuter);

526 527
  if (!rguid || !pvOut) return E_POINTER;

528
  /* Loop on all the devices to see if anyone matches the given GUID */
529
  for (i = 0; i < NB_DINPUT_DEVICES; i++) {
530
    HRESULT ret;
531

532
    if (!dinput_devices[i]->create_deviceW) continue;
533
    if ((ret = dinput_devices[i]->create_deviceW(This, rguid, riid, (LPDIRECTINPUTDEVICEW*) pvOut)) == DI_OK)
534 535 536 537
    {
      EnterCriticalSection( &This->crit );
      list_add_tail( &This->devices_list, &(*(IDirectInputDevice2AImpl**)pvOut)->entry );
      LeaveCriticalSection( &This->crit );
538
      return DI_OK;
539
    }
540 541 542 543 544 545 546 547

    if (ret == DIERR_NOINTERFACE)
      ret_value = DIERR_NOINTERFACE;
  }

  return ret_value;
}

548 549 550 551 552 553 554 555 556 557 558 559
static HRESULT WINAPI IDirectInputAImpl_CreateDevice(LPDIRECTINPUT7A iface, REFGUID rguid,
                                                     LPDIRECTINPUTDEVICEA* pdev, LPUNKNOWN punk)
{
    return IDirectInput7AImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
}

static HRESULT WINAPI IDirectInputWImpl_CreateDevice(LPDIRECTINPUT7W iface, REFGUID rguid,
                                                     LPDIRECTINPUTDEVICEW* pdev, LPUNKNOWN punk)
{
    return IDirectInput7WImpl_CreateDeviceEx(iface, rguid, NULL, (LPVOID*)pdev, punk);
}

560 561 562
/*******************************************************************************
 *      DirectInput8
 */
563

564 565 566 567
static ULONG WINAPI IDirectInput8AImpl_AddRef(LPDIRECTINPUT8A iface)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInputAImpl_AddRef( (IDirectInput7A *)This );
568 569
}

570 571 572 573 574
static ULONG WINAPI IDirectInput8WImpl_AddRef(LPDIRECTINPUT8W iface)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInputAImpl_AddRef( (IDirectInput7A *)This );
}
575

576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
static HRESULT WINAPI IDirectInput8AImpl_QueryInterface(LPDIRECTINPUT8A iface, REFIID riid, LPVOID *ppobj)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInputAImpl_QueryInterface( (IDirectInput7A *)This, riid, ppobj );
}

static HRESULT WINAPI IDirectInput8WImpl_QueryInterface(LPDIRECTINPUT8W iface, REFIID riid, LPVOID *ppobj)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInputAImpl_QueryInterface( (IDirectInput7A *)This, riid, ppobj );
}

static ULONG WINAPI IDirectInput8AImpl_Release(LPDIRECTINPUT8A iface)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInputAImpl_Release( (IDirectInput7A *)This );
}

static ULONG WINAPI IDirectInput8WImpl_Release(LPDIRECTINPUT8W iface)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInputAImpl_Release( (IDirectInput7A *)This );
}

static HRESULT WINAPI IDirectInput8AImpl_CreateDevice(LPDIRECTINPUT8A iface, REFGUID rguid,
                                                      LPDIRECTINPUTDEVICE8A* pdev, LPUNKNOWN punk)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInput7AImpl_CreateDeviceEx( (IDirectInput7A *)This, rguid, NULL, (LPVOID*)pdev, punk );
}

static HRESULT WINAPI IDirectInput8WImpl_CreateDevice(LPDIRECTINPUT8W iface, REFGUID rguid,
                                                      LPDIRECTINPUTDEVICE8W* pdev, LPUNKNOWN punk)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInput7WImpl_CreateDeviceEx( IDirectInput7W_from_impl( This ), rguid, NULL, (LPVOID*)pdev, punk );
}

static HRESULT WINAPI IDirectInput8AImpl_EnumDevices(LPDIRECTINPUT8A iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKA lpCallback,
                                                     LPVOID pvRef, DWORD dwFlags)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInputAImpl_EnumDevices( (IDirectInput7A *)This, dwDevType, lpCallback, pvRef, dwFlags );
}

static HRESULT WINAPI IDirectInput8WImpl_EnumDevices(LPDIRECTINPUT8W iface, DWORD dwDevType, LPDIENUMDEVICESCALLBACKW lpCallback,
                                                     LPVOID pvRef, DWORD dwFlags)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInputWImpl_EnumDevices( IDirectInput7W_from_impl( This ), dwDevType, lpCallback, pvRef, dwFlags );
}

static HRESULT WINAPI IDirectInput8AImpl_GetDeviceStatus(LPDIRECTINPUT8A iface, REFGUID rguid)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInputAImpl_GetDeviceStatus( (IDirectInput7A *)This, rguid );
}

static HRESULT WINAPI IDirectInput8WImpl_GetDeviceStatus(LPDIRECTINPUT8W iface, REFGUID rguid)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInputAImpl_GetDeviceStatus( (IDirectInput7A *)This, rguid );
}

static HRESULT WINAPI IDirectInput8AImpl_RunControlPanel(LPDIRECTINPUT8A iface, HWND hwndOwner, DWORD dwFlags)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInputAImpl_RunControlPanel( (IDirectInput7A *)This, hwndOwner, dwFlags );
}

static HRESULT WINAPI IDirectInput8WImpl_RunControlPanel(LPDIRECTINPUT8W iface, HWND hwndOwner, DWORD dwFlags)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInputAImpl_RunControlPanel( (IDirectInput7A *)This, hwndOwner, dwFlags );
}

static HRESULT WINAPI IDirectInput8AImpl_Initialize(LPDIRECTINPUT8A iface, HINSTANCE hinst, DWORD x)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInputAImpl_Initialize( (IDirectInput7A *)This, hinst, x );
}

static HRESULT WINAPI IDirectInput8WImpl_Initialize(LPDIRECTINPUT8W iface, HINSTANCE hinst, DWORD x)
{
    IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
    return IDirectInputAImpl_Initialize( (IDirectInput7A *)This, hinst, x );
}

static HRESULT WINAPI IDirectInput8AImpl_FindDevice(LPDIRECTINPUT8A iface, REFGUID rguid, LPCSTR pszName, LPGUID pguidInstance)
{
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
    return IDirectInput2AImpl_FindDevice( (IDirectInput7A *)This, rguid, pszName, pguidInstance );
}

static HRESULT WINAPI IDirectInput8WImpl_FindDevice(LPDIRECTINPUT8W iface, REFGUID rguid, LPCWSTR pszName, LPGUID pguidInstance)
{
    IDirectInput7W *This = IDirectInput7W_from_impl( impl_from_IDirectInput8W( iface ) );
    return IDirectInput2WImpl_FindDevice( This, rguid, pszName, pguidInstance );
674 675 676 677 678 679 680 681
}

static HRESULT WINAPI IDirectInput8AImpl_EnumDevicesBySemantics(
      LPDIRECTINPUT8A iface, LPCSTR ptszUserName, LPDIACTIONFORMATA lpdiActionFormat,
      LPDIENUMDEVICESBYSEMANTICSCBA lpCallback,
      LPVOID pvRef, DWORD dwFlags
)
{
682
    IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
683

684 685 686 687 688 689 690 691 692 693 694 695 696 697
    FIXME("(this=%p,%s,%p,%p,%p,%04x): stub\n", This, ptszUserName, lpdiActionFormat,
          lpCallback, pvRef, dwFlags);
#define X(x) if (dwFlags & x) FIXME("\tdwFlags |= "#x"\n");
	X(DIEDBSFL_ATTACHEDONLY)
	X(DIEDBSFL_THISUSER)
	X(DIEDBSFL_FORCEFEEDBACK)
	X(DIEDBSFL_AVAILABLEDEVICES)
	X(DIEDBSFL_MULTIMICEKEYBOARDS)
	X(DIEDBSFL_NONGAMINGDEVICES)
#undef X

    _dump_diactionformatA(lpdiActionFormat);

    return DI_OK;
698 699
}

700 701 702 703 704 705
static HRESULT WINAPI IDirectInput8WImpl_EnumDevicesBySemantics(
      LPDIRECTINPUT8W iface, LPCWSTR ptszUserName, LPDIACTIONFORMATW lpdiActionFormat,
      LPDIENUMDEVICESBYSEMANTICSCBW lpCallback,
      LPVOID pvRef, DWORD dwFlags
)
{
706
      IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
707

708
      FIXME("(this=%p,%s,%p,%p,%p,%04x): stub\n", This, debugstr_w(ptszUserName), lpdiActionFormat,
709 710 711 712
            lpCallback, pvRef, dwFlags);
      return 0;
}

713 714 715 716 717
static HRESULT WINAPI IDirectInput8AImpl_ConfigureDevices(
      LPDIRECTINPUT8A iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
      LPDICONFIGUREDEVICESPARAMSA lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
)
{
718
      IDirectInputImpl *This = impl_from_IDirectInput8A( iface );
719

720
      FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
721 722 723 724 725 726 727 728 729
            dwFlags, pvRefData);
      return 0;
}

static HRESULT WINAPI IDirectInput8WImpl_ConfigureDevices(
      LPDIRECTINPUT8W iface, LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
      LPDICONFIGUREDEVICESPARAMSW lpdiCDParams, DWORD dwFlags, LPVOID pvRefData
)
{
730
      IDirectInputImpl *This = impl_from_IDirectInput8W( iface );
731

732
      FIXME("(this=%p,%p,%p,%04x,%p): stub\n", This, lpdiCallback, lpdiCDParams,
733 734 735 736
            dwFlags, pvRefData);
      return 0;
}

737
static const IDirectInput7AVtbl ddi7avt = {
738 739 740 741 742 743 744 745 746 747
    IDirectInputAImpl_QueryInterface,
    IDirectInputAImpl_AddRef,
    IDirectInputAImpl_Release,
    IDirectInputAImpl_CreateDevice,
    IDirectInputAImpl_EnumDevices,
    IDirectInputAImpl_GetDeviceStatus,
    IDirectInputAImpl_RunControlPanel,
    IDirectInputAImpl_Initialize,
    IDirectInput2AImpl_FindDevice,
    IDirectInput7AImpl_CreateDeviceEx
748 749
};

750
static const IDirectInput7WVtbl ddi7wvt = {
751 752 753 754 755 756 757 758 759 760
    IDirectInputWImpl_QueryInterface,
    IDirectInputWImpl_AddRef,
    IDirectInputWImpl_Release,
    IDirectInputWImpl_CreateDevice,
    IDirectInputWImpl_EnumDevices,
    IDirectInputWImpl_GetDeviceStatus,
    IDirectInputWImpl_RunControlPanel,
    IDirectInputWImpl_Initialize,
    IDirectInput2WImpl_FindDevice,
    IDirectInput7WImpl_CreateDeviceEx
Alexandre Julliard's avatar
Alexandre Julliard committed
761
};
762

763
static const IDirectInput8AVtbl ddi8avt = {
764 765 766 767 768 769 770 771 772 773 774
    IDirectInput8AImpl_QueryInterface,
    IDirectInput8AImpl_AddRef,
    IDirectInput8AImpl_Release,
    IDirectInput8AImpl_CreateDevice,
    IDirectInput8AImpl_EnumDevices,
    IDirectInput8AImpl_GetDeviceStatus,
    IDirectInput8AImpl_RunControlPanel,
    IDirectInput8AImpl_Initialize,
    IDirectInput8AImpl_FindDevice,
    IDirectInput8AImpl_EnumDevicesBySemantics,
    IDirectInput8AImpl_ConfigureDevices
775 776
};

777
static const IDirectInput8WVtbl ddi8wvt = {
778 779 780 781 782 783 784 785 786 787 788
    IDirectInput8WImpl_QueryInterface,
    IDirectInput8WImpl_AddRef,
    IDirectInput8WImpl_Release,
    IDirectInput8WImpl_CreateDevice,
    IDirectInput8WImpl_EnumDevices,
    IDirectInput8WImpl_GetDeviceStatus,
    IDirectInput8WImpl_RunControlPanel,
    IDirectInput8WImpl_Initialize,
    IDirectInput8WImpl_FindDevice,
    IDirectInput8WImpl_EnumDevicesBySemantics,
    IDirectInput8WImpl_ConfigureDevices
Alexandre Julliard's avatar
Alexandre Julliard committed
789
};
790

791 792 793 794 795 796
/*******************************************************************************
 * DirectInput ClassFactory
 */
typedef struct
{
    /* IUnknown fields */
797
    const IClassFactoryVtbl    *lpVtbl;
798
    LONG                        ref;
799 800 801
} IClassFactoryImpl;

static HRESULT WINAPI DICF_QueryInterface(LPCLASSFACTORY iface,REFIID riid,LPVOID *ppobj) {
802
	IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
803 804 805 806 807 808

	FIXME("(%p)->(%s,%p),stub!\n",This,debugstr_guid(riid),ppobj);
	return E_NOINTERFACE;
}

static ULONG WINAPI DICF_AddRef(LPCLASSFACTORY iface) {
809
	IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
810
	return InterlockedIncrement(&(This->ref));
811 812 813
}

static ULONG WINAPI DICF_Release(LPCLASSFACTORY iface) {
814
	IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
815
	/* static class, won't be  freed */
816
	return InterlockedDecrement(&(This->ref));
817 818 819 820 821
}

static HRESULT WINAPI DICF_CreateInstance(
	LPCLASSFACTORY iface,LPUNKNOWN pOuter,REFIID riid,LPVOID *ppobj
) {
822
	IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
823 824

	TRACE("(%p)->(%p,%s,%p)\n",This,pOuter,debugstr_guid(riid),ppobj);
825 826
        if ( IsEqualGUID( &IID_IUnknown, riid ) ||
             IsEqualGUID( &IID_IDirectInputA, riid ) ||
827
	     IsEqualGUID( &IID_IDirectInputW, riid ) ||
828
	     IsEqualGUID( &IID_IDirectInput2A, riid ) ||
829
	     IsEqualGUID( &IID_IDirectInput2W, riid ) ||
830
	     IsEqualGUID( &IID_IDirectInput7A, riid ) ||
831 832 833
	     IsEqualGUID( &IID_IDirectInput7W, riid ) ||
	     IsEqualGUID( &IID_IDirectInput8A, riid ) ||
	     IsEqualGUID( &IID_IDirectInput8W, riid ) ) {
834 835 836 837 838 839 840 841 842
		/* FIXME: reuse already created dinput if present? */
		return DirectInputCreateEx(0,0,riid,ppobj,pOuter);
	}

	FIXME("(%p,%p,%s,%p) Interface not found!\n",This,pOuter,debugstr_guid(riid),ppobj);	
	return E_NOINTERFACE;
}

static HRESULT WINAPI DICF_LockServer(LPCLASSFACTORY iface,BOOL dolock) {
843
	IClassFactoryImpl *This = (IClassFactoryImpl *)iface;
844 845 846 847
	FIXME("(%p)->(%d),stub!\n",This,dolock);
	return S_OK;
}

848
static const IClassFactoryVtbl DICF_Vtbl = {
849 850 851 852 853 854 855 856
	DICF_QueryInterface,
	DICF_AddRef,
	DICF_Release,
	DICF_CreateInstance,
	DICF_LockServer
};
static IClassFactoryImpl DINPUT_CF = {&DICF_Vtbl, 1 };

857 858 859
/***********************************************************************
 *		DllCanUnloadNow (DINPUT.@)
 */
860
HRESULT WINAPI DllCanUnloadNow(void)
861 862 863 864 865 866 867
{
    return S_FALSE;
}

/***********************************************************************
 *		DllGetClassObject (DINPUT.@)
 */
868
HRESULT WINAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
869
{
870
    TRACE("(%s,%s,%p)\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
871
    if ( IsEqualCLSID( &IID_IClassFactory, riid ) ) {
872
        *ppv = &DINPUT_CF;
873 874 875
	IClassFactory_AddRef((IClassFactory*)*ppv);
    return S_OK;
    }
876

877
    FIXME("(%s,%s,%p): no interface found.\n", debugstr_guid(rclsid), debugstr_guid(riid), ppv);
878 879
    return CLASS_E_CLASSNOTAVAILABLE;
}
880 881 882 883 884

/******************************************************************************
 *	DInput hook thread
 */

885 886 887
static LRESULT CALLBACK LL_hook_proc( int code, WPARAM wparam, LPARAM lparam )
{
    IDirectInputImpl *dinput;
888
    int skip = 0;
889 890 891 892 893 894 895 896 897 898 899 900 901

    if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );

    EnterCriticalSection( &dinput_hook_crit );
    LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
    {
        IDirectInputDevice2AImpl *dev;

        EnterCriticalSection( &dinput->crit );
        LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDevice2AImpl, entry )
            if (dev->acquired && dev->event_proc)
            {
                TRACE("calling %p->%p (%lx %lx)\n", dev, dev->event_proc, wparam, lparam);
902
                skip |= dev->event_proc( (LPDIRECTINPUTDEVICE8A)dev, wparam, lparam );
903 904 905 906 907
            }
        LeaveCriticalSection( &dinput->crit );
    }
    LeaveCriticalSection( &dinput_hook_crit );

908
    return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
909 910
}

911 912 913 914 915 916
static LRESULT CALLBACK callwndproc_proc( int code, WPARAM wparam, LPARAM lparam )
{
    CWPSTRUCT *msg = (CWPSTRUCT *)lparam;
    IDirectInputImpl *dinput;
    HWND foreground;

917 918
    if (code != HC_ACTION || (msg->message != WM_KILLFOCUS &&
        msg->message != WM_ACTIVATEAPP && msg->message != WM_ACTIVATE))
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
        return CallNextHookEx( 0, code, wparam, lparam );

    foreground = GetForegroundWindow();

    EnterCriticalSection( &dinput_hook_crit );

    LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
    {
        IDirectInputDevice2AImpl *dev;

        EnterCriticalSection( &dinput->crit );
        LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDevice2AImpl, entry )
        {
            if (!dev->acquired) continue;

            if (msg->hwnd == dev->win && msg->hwnd != foreground)
            {
                TRACE( "%p window is not foreground - unacquiring %p\n", dev->win, dev );
                IDirectInputDevice_Unacquire( (LPDIRECTINPUTDEVICE8A)dev );
            }
        }
        LeaveCriticalSection( &dinput->crit );
    }
    LeaveCriticalSection( &dinput_hook_crit );

    return CallNextHookEx( 0, code, wparam, lparam );
}

947
static DWORD WINAPI hook_thread_proc(void *param)
948 949
{
    static HHOOK kbd_hook, mouse_hook;
950 951 952 953 954
    MSG msg;

    /* Force creation of the message queue */
    PeekMessageW( &msg, 0, 0, 0, PM_NOREMOVE );
    SetEvent(*(LPHANDLE)param);
955

956
    while (GetMessageW( &msg, 0, 0, 0 ))
957
    {
958 959 960
        UINT kbd_cnt = 0, mice_cnt = 0;

        if (msg.message == WM_USER+0x10)
961
        {
962 963
            IDirectInputImpl *dinput;

964 965 966
            TRACE( "Processing hook change notification lp:%ld\n", msg.lParam );

            if (!msg.wParam && !msg.lParam)
967
            {
968 969 970 971
                if (kbd_hook) UnhookWindowsHookEx( kbd_hook );
                if (mouse_hook) UnhookWindowsHookEx( mouse_hook );
                kbd_hook = mouse_hook = NULL;
                break;
972
            }
973 974 975 976 977

            EnterCriticalSection( &dinput_hook_crit );

            /* Count acquired keyboards and mice*/
            LIST_FOR_EACH_ENTRY( dinput, &direct_input_list, IDirectInputImpl, entry )
978
            {
979 980 981 982 983
                IDirectInputDevice2AImpl *dev;

                EnterCriticalSection( &dinput->crit );
                LIST_FOR_EACH_ENTRY( dev, &dinput->devices_list, IDirectInputDevice2AImpl, entry )
                {
984
                    if (!dev->acquired || !dev->event_proc) continue;
985 986 987 988 989 990 991 992 993 994

                    if (IsEqualGUID( &dev->guid, &GUID_SysKeyboard ) ||
                        IsEqualGUID( &dev->guid, &DInput_Wine_Keyboard_GUID ))
                        kbd_cnt++;
                    else
                        if (IsEqualGUID( &dev->guid, &GUID_SysMouse ) ||
                            IsEqualGUID( &dev->guid, &DInput_Wine_Mouse_GUID ))
                            mice_cnt++;
                }
                LeaveCriticalSection( &dinput->crit );
995
            }
996 997 998 999 1000
            LeaveCriticalSection( &dinput_hook_crit );

            if (kbd_cnt && !kbd_hook)
                kbd_hook = SetWindowsHookExW( WH_KEYBOARD_LL, LL_hook_proc, DINPUT_instance, 0 );
            else if (!kbd_cnt && kbd_hook)
1001
            {
1002 1003
                UnhookWindowsHookEx( kbd_hook );
                kbd_hook = NULL;
1004
            }
1005 1006 1007 1008

            if (mice_cnt && !mouse_hook)
                mouse_hook = SetWindowsHookExW( WH_MOUSE_LL, LL_hook_proc, DINPUT_instance, 0 );
            else if (!mice_cnt && mouse_hook)
1009
            {
1010
                UnhookWindowsHookEx( mouse_hook );
1011 1012 1013
                mouse_hook = NULL;
            }
        }
1014 1015
        TranslateMessage(&msg);
        DispatchMessageW(&msg);
1016 1017 1018 1019 1020
    }

    return 0;
}

1021 1022
static DWORD hook_thread_id;

1023 1024 1025 1026 1027 1028 1029 1030
static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
{
    0, 0, &dinput_hook_crit,
    { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
};
static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };

1031
static BOOL check_hook_thread(void)
1032
{
1033 1034
    static HANDLE hook_thread;

1035
    EnterCriticalSection(&dinput_hook_crit);
1036

1037 1038
    TRACE("IDirectInputs left: %d\n", list_count(&direct_input_list));
    if (!list_empty(&direct_input_list) && !hook_thread)
1039
    {
1040 1041
        HANDLE event;

1042
        event = CreateEventW(NULL, FALSE, FALSE, NULL);
1043
        hook_thread = CreateThread(NULL, 0, hook_thread_proc, &event, 0, &hook_thread_id);
1044
        if (event && hook_thread)
1045 1046
        {
            HANDLE handles[2];
1047
            handles[0] = event;
1048
            handles[1] = hook_thread;
1049 1050
            WaitForMultipleObjects(2, handles, FALSE, INFINITE);
        }
1051
        LeaveCriticalSection(&dinput_hook_crit);
1052
        CloseHandle(event);
1053
    }
1054
    else if (list_empty(&direct_input_list) && hook_thread)
1055
    {
1056 1057 1058 1059 1060 1061
        DWORD tid = hook_thread_id;

        hook_thread_id = 0;
        PostThreadMessageW(tid, WM_USER+0x10, 0, 0);
        LeaveCriticalSection(&dinput_hook_crit);

1062 1063 1064
        /* wait for hook thread to exit */
        WaitForSingleObject(hook_thread, INFINITE);
        CloseHandle(hook_thread);
1065
        hook_thread = NULL;
1066
    }
1067 1068
    else
        LeaveCriticalSection(&dinput_hook_crit);
1069

1070
    return hook_thread_id != 0;
1071 1072
}

1073
void check_dinput_hooks(LPDIRECTINPUTDEVICE8A iface)
1074
{
1075 1076 1077 1078
    static HHOOK callwndproc_hook;
    static ULONG foreground_cnt;
    IDirectInputDevice2AImpl *dev = (IDirectInputDevice2AImpl *)iface;

1079
    EnterCriticalSection(&dinput_hook_crit);
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097

    if (dev->dwCoopLevel & DISCL_FOREGROUND)
    {
        if (dev->acquired)
            foreground_cnt++;
        else
            foreground_cnt--;
    }

    if (foreground_cnt && !callwndproc_hook)
        callwndproc_hook = SetWindowsHookExW( WH_CALLWNDPROC, callwndproc_proc,
                                              DINPUT_instance, GetCurrentThreadId() );
    else if (!foreground_cnt && callwndproc_hook)
    {
        UnhookWindowsHookEx( callwndproc_hook );
        callwndproc_hook = NULL;
    }

1098
    PostThreadMessageW( hook_thread_id, WM_USER+0x10, 1, 0 );
1099

1100
    LeaveCriticalSection(&dinput_hook_crit);
1101
}