include/mscvpdb.h: Use flexible array members for the rest of structures.
[wine.git] / dlls / dinput / dinput_main.c
blob8f22b6c3057728f182df363366b728b67a058dac
1 /* DirectInput
3 * Copyright 1998 Marcus Meissner
4 * Copyright 1998,1999 Lionel Ulmer
5 * Copyright 2000-2002 TransGaming Technologies Inc.
6 * Copyright 2007 Vitaliy Margolen
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.
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.
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
24 #include <assert.h>
25 #include <stdarg.h>
26 #include <string.h>
28 #define COBJMACROS
29 #include "windef.h"
30 #include "winbase.h"
31 #include "winuser.h"
32 #include "winerror.h"
33 #include "objbase.h"
34 #include "rpcproxy.h"
35 #include "devguid.h"
36 #include "hidusage.h"
37 #include "initguid.h"
38 #include "dinputd.h"
40 #include "dinput_private.h"
41 #include "device_private.h"
43 #include "wine/asm.h"
44 #include "wine/debug.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(dinput);
48 #define INPUT_THREAD_NOTIFY (WM_USER + 0x10)
49 #define NOTIFY_THREAD_STOP 0
50 #define NOTIFY_REFRESH_DEVICES 1
52 struct input_thread_state
54 BOOL running;
55 UINT events_count;
56 UINT devices_count;
57 UINT devices_capacity;
58 HHOOK mouse_ll_hook;
59 HHOOK keyboard_ll_hook;
60 RAWINPUTDEVICE rawinput_devices[2];
61 struct dinput_device **devices;
62 HANDLE *events;
65 static inline struct dinput_device *impl_from_IDirectInputDevice8W( IDirectInputDevice8W *iface )
67 return CONTAINING_RECORD( iface, struct dinput_device, IDirectInputDevice8W_iface );
70 HINSTANCE DINPUT_instance;
72 static HWND di_em_win;
73 static HANDLE dinput_thread;
74 static UINT input_thread_user_count;
75 static struct input_thread_state *input_thread_state;
77 static CRITICAL_SECTION dinput_hook_crit;
78 static CRITICAL_SECTION_DEBUG dinput_critsect_debug =
80 0, 0, &dinput_hook_crit,
81 { &dinput_critsect_debug.ProcessLocksList, &dinput_critsect_debug.ProcessLocksList },
82 0, 0, { (DWORD_PTR)(__FILE__ ": dinput_hook_crit") }
84 static CRITICAL_SECTION dinput_hook_crit = { &dinput_critsect_debug, -1, 0, 0, 0, 0 };
86 static struct list acquired_device_list = LIST_INIT( acquired_device_list );
88 static void unhook_device_window_foreground_changes( struct dinput_device *device )
90 if (!device->cbt_hook) return;
91 UnhookWindowsHookEx( device->cbt_hook );
92 device->cbt_hook = NULL;
95 static void dinput_device_internal_unacquire( IDirectInputDevice8W *iface, DWORD status )
97 struct dinput_device *impl = impl_from_IDirectInputDevice8W( iface );
99 TRACE( "iface %p.\n", iface );
101 unhook_device_window_foreground_changes( impl );
103 EnterCriticalSection( &impl->crit );
104 if (impl->status == STATUS_ACQUIRED)
106 impl->vtbl->unacquire( iface );
107 impl->status = status;
108 list_remove( &impl->entry );
110 LeaveCriticalSection( &impl->crit );
113 static LRESULT CALLBACK input_thread_ll_hook_proc( int code, WPARAM wparam, LPARAM lparam )
115 struct input_thread_state *state = input_thread_state;
116 int i, skip = 0;
118 if (code != HC_ACTION) return CallNextHookEx( 0, code, wparam, lparam );
120 for (i = state->events_count; i < state->devices_count; ++i)
122 struct dinput_device *device = state->devices[i];
123 if (device->use_raw_input) continue;
124 if (device->instance.dwDevType & DIDEVTYPE_HID) continue;
125 switch (GET_DIDEVICE_TYPE( device->instance.dwDevType ))
127 case DIDEVTYPE_MOUSE:
128 case DI8DEVTYPE_MOUSE:
129 TRACE( "calling dinput_mouse_hook (%p %Ix %Ix)\n", device, wparam, lparam );
130 skip |= dinput_mouse_hook( &device->IDirectInputDevice8W_iface, wparam, lparam );
131 break;
132 case DIDEVTYPE_KEYBOARD:
133 case DI8DEVTYPE_KEYBOARD:
134 TRACE( "calling dinput_keyboard_hook (%p %Ix %Ix)\n", device, wparam, lparam );
135 skip |= dinput_keyboard_hook( &device->IDirectInputDevice8W_iface, wparam, lparam );
136 break;
140 return skip ? 1 : CallNextHookEx( 0, code, wparam, lparam );
143 static void handle_foreground_lost( HWND window )
145 struct dinput_device *impl, *next;
147 EnterCriticalSection( &dinput_hook_crit );
149 LIST_FOR_EACH_ENTRY_SAFE( impl, next, &acquired_device_list, struct dinput_device, entry )
151 if (!(impl->dwCoopLevel & DISCL_FOREGROUND) || window != impl->win) continue;
152 TRACE( "%p window is not foreground - unacquiring %p\n", impl->win, impl );
153 dinput_device_internal_unacquire( &impl->IDirectInputDevice8W_iface, STATUS_UNACQUIRED );
156 LeaveCriticalSection( &dinput_hook_crit );
159 static void dinput_unacquire_devices(void)
161 struct dinput_device *impl, *next;
163 EnterCriticalSection( &dinput_hook_crit );
165 LIST_FOR_EACH_ENTRY_SAFE( impl, next, &acquired_device_list, struct dinput_device, entry )
166 dinput_device_internal_unacquire( &impl->IDirectInputDevice8W_iface, STATUS_UNACQUIRED );
168 LeaveCriticalSection( &dinput_hook_crit );
171 static LRESULT CALLBACK cbt_hook_proc( int code, WPARAM wparam, LPARAM lparam )
173 if (code == HCBT_ACTIVATE && di_em_win)
175 CBTACTIVATESTRUCT *data = (CBTACTIVATESTRUCT *)lparam;
176 handle_foreground_lost( data->hWndActive );
177 SendMessageW( di_em_win, INPUT_THREAD_NOTIFY, NOTIFY_REFRESH_DEVICES, 0 );
180 return CallNextHookEx( 0, code, wparam, lparam );
183 static void hook_device_window_foreground_changes( struct dinput_device *device )
185 DWORD tid, pid;
186 if (!(tid = GetWindowThreadProcessId( device->win, &pid ))) return;
187 device->cbt_hook = SetWindowsHookExW( WH_CBT, cbt_hook_proc, DINPUT_instance, tid );
190 static void input_thread_update_device_list( struct input_thread_state *state )
192 RAWINPUTDEVICE rawinput_keyboard = {.usUsagePage = HID_USAGE_PAGE_GENERIC, .usUsage = HID_USAGE_GENERIC_KEYBOARD, .dwFlags = RIDEV_REMOVE};
193 RAWINPUTDEVICE rawinput_mouse = {.usUsagePage = HID_USAGE_PAGE_GENERIC, .usUsage = HID_USAGE_GENERIC_MOUSE, .dwFlags = RIDEV_REMOVE};
194 UINT count = 0, keyboard_ll_count = 0, mouse_ll_count = 0, capacity;
195 struct dinput_device *device;
197 EnterCriticalSection( &dinput_hook_crit );
199 if ((capacity = list_count( &acquired_device_list )) && capacity > state->devices_capacity)
201 struct dinput_device **devices;
202 HANDLE *events;
204 if (!state->devices_capacity) capacity = max( capacity, 128 );
205 else capacity = max( capacity, state->devices_capacity * 3 / 2 );
207 if ((events = realloc( state->events, capacity * sizeof(*events) ))) state->events = events;
208 if ((devices = realloc( state->devices, capacity * sizeof(*devices) ))) state->devices = devices;
209 if (events && devices) state->devices_capacity = capacity;
212 LIST_FOR_EACH_ENTRY( device, &acquired_device_list, struct dinput_device, entry )
214 unhook_device_window_foreground_changes( device );
215 if (device->dwCoopLevel & DISCL_FOREGROUND) hook_device_window_foreground_changes( device );
217 if (!device->read_event || !device->vtbl->read) continue;
218 state->events[count] = device->read_event;
219 dinput_device_internal_addref( (state->devices[count] = device) );
220 if (++count >= state->devices_capacity) break;
222 state->events_count = count;
224 LIST_FOR_EACH_ENTRY( device, &acquired_device_list, struct dinput_device, entry )
226 RAWINPUTDEVICE *rawinput_device = NULL;
228 if (device->read_event && device->vtbl->read) continue;
229 switch (GET_DIDEVICE_TYPE( device->instance.dwDevType ))
231 case DIDEVTYPE_MOUSE:
232 case DI8DEVTYPE_MOUSE:
233 if (device->dwCoopLevel & DISCL_EXCLUSIVE) rawinput_mouse.dwFlags |= RIDEV_CAPTUREMOUSE;
234 if (!device->use_raw_input) mouse_ll_count++;
235 else rawinput_device = &rawinput_mouse;
236 break;
237 case DIDEVTYPE_KEYBOARD:
238 case DI8DEVTYPE_KEYBOARD:
239 if (device->dwCoopLevel & DISCL_EXCLUSIVE) rawinput_keyboard.dwFlags |= RIDEV_NOHOTKEYS;
240 if (!device->use_raw_input) keyboard_ll_count++;
241 else rawinput_device = &rawinput_keyboard;
242 break;
245 if (rawinput_device)
247 if (device->dwCoopLevel & DISCL_BACKGROUND) rawinput_device->dwFlags |= RIDEV_INPUTSINK;
248 if (device->dwCoopLevel & DISCL_EXCLUSIVE) rawinput_device->dwFlags |= RIDEV_NOLEGACY;
249 rawinput_device->dwFlags &= ~RIDEV_REMOVE;
250 rawinput_device->hwndTarget = di_em_win;
253 dinput_device_internal_addref( (state->devices[count] = device) );
254 if (++count >= state->devices_capacity) break;
256 state->devices_count = count;
257 LeaveCriticalSection( &dinput_hook_crit );
259 if (keyboard_ll_count && !state->keyboard_ll_hook)
260 state->keyboard_ll_hook = SetWindowsHookExW( WH_KEYBOARD_LL, input_thread_ll_hook_proc, DINPUT_instance, 0 );
261 else if (!keyboard_ll_count && state->keyboard_ll_hook)
263 UnhookWindowsHookEx( state->keyboard_ll_hook );
264 state->keyboard_ll_hook = NULL;
267 if (mouse_ll_count && !state->mouse_ll_hook)
268 state->mouse_ll_hook = SetWindowsHookExW( WH_MOUSE_LL, input_thread_ll_hook_proc, DINPUT_instance, 0 );
269 else if (!mouse_ll_count && state->mouse_ll_hook)
271 UnhookWindowsHookEx( state->mouse_ll_hook );
272 state->mouse_ll_hook = NULL;
275 if (!rawinput_mouse.hwndTarget != !state->rawinput_devices[0].hwndTarget &&
276 !RegisterRawInputDevices( &rawinput_mouse, 1, sizeof(RAWINPUTDEVICE) ))
277 WARN( "Failed to (un)register rawinput mouse device.\n" );
278 if (!rawinput_keyboard.hwndTarget != !state->rawinput_devices[1].hwndTarget &&
279 !RegisterRawInputDevices( &rawinput_keyboard, 1, sizeof(RAWINPUTDEVICE) ))
280 WARN( "Failed to (un)register rawinput mouse device.\n" );
282 state->rawinput_devices[0] = rawinput_mouse;
283 state->rawinput_devices[1] = rawinput_keyboard;
286 static LRESULT WINAPI di_em_win_wndproc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
288 struct input_thread_state *state = input_thread_state;
289 int rim = GET_RAWINPUT_CODE_WPARAM( wparam );
290 UINT i, size = sizeof(RAWINPUT);
291 RAWINPUT ri;
293 TRACE( "%p %d %Ix %Ix\n", hwnd, msg, wparam, lparam );
295 if (msg == WM_INPUT && (rim == RIM_INPUT || rim == RIM_INPUTSINK))
297 size = GetRawInputData( (HRAWINPUT)lparam, RID_INPUT, &ri, &size, sizeof(RAWINPUTHEADER) );
298 if (size == (UINT)-1 || size < sizeof(RAWINPUTHEADER))
299 WARN( "Unable to read raw input data\n" );
300 else if (ri.header.dwType == RIM_TYPEHID)
301 WARN( "Unexpected HID rawinput message\n" );
302 else
304 for (i = state->events_count; i < state->devices_count; ++i)
306 struct dinput_device *device = state->devices[i];
307 if (!device->use_raw_input) continue;
308 if (device->instance.dwDevType & DIDEVTYPE_HID) continue;
309 switch (GET_DIDEVICE_TYPE( device->instance.dwDevType ))
311 case DIDEVTYPE_MOUSE:
312 case DI8DEVTYPE_MOUSE:
313 if (ri.header.dwType != RIM_TYPEMOUSE) break;
314 dinput_mouse_rawinput_hook( &device->IDirectInputDevice8W_iface, wparam, lparam, &ri );
315 break;
316 case DIDEVTYPE_KEYBOARD:
317 case DI8DEVTYPE_KEYBOARD:
318 if (ri.header.dwType != RIM_TYPEKEYBOARD) break;
319 dinput_keyboard_rawinput_hook( &device->IDirectInputDevice8W_iface, wparam, lparam, &ri );
320 break;
321 default: break;
327 if (msg == INPUT_THREAD_NOTIFY)
329 TRACE( "Processing hook change notification wparam %#Ix, lparam %#Ix.\n", wparam, lparam );
331 switch (wparam)
333 case NOTIFY_THREAD_STOP:
334 state->running = FALSE;
335 break;
336 case NOTIFY_REFRESH_DEVICES:
337 while (state->devices_count--) dinput_device_internal_release( state->devices[state->devices_count] );
338 input_thread_update_device_list( state );
339 break;
342 return 0;
345 return DefWindowProcW( hwnd, msg, wparam, lparam );
348 static void register_di_em_win_class(void)
350 WNDCLASSEXW class;
352 memset(&class, 0, sizeof(class));
353 class.cbSize = sizeof(class);
354 class.lpfnWndProc = di_em_win_wndproc;
355 class.hInstance = DINPUT_instance;
356 class.lpszClassName = L"DIEmWin";
358 if (!RegisterClassExW( &class ) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS)
359 WARN( "Unable to register message window class\n" );
362 static void unregister_di_em_win_class(void)
364 if (!UnregisterClassW( L"DIEmWin", NULL ) && GetLastError() != ERROR_CLASS_DOES_NOT_EXIST)
365 WARN( "Unable to unregister message window class\n" );
368 static DWORD WINAPI dinput_thread_proc( void *params )
370 struct input_thread_state state = {.running = TRUE};
371 struct dinput_device *device;
372 HANDLE start_event = params;
373 DWORD ret;
374 MSG msg;
376 SetThreadDescription( GetCurrentThread(), L"wine_dinput_worker" );
378 di_em_win = CreateWindowW( L"DIEmWin", L"DIEmWin", 0, 0, 0, 0, 0, HWND_MESSAGE, 0, DINPUT_instance, NULL );
379 input_thread_state = &state;
380 SetEvent( start_event );
382 while (state.running && (ret = MsgWaitForMultipleObjectsEx( state.events_count, state.events, INFINITE, QS_ALLINPUT, 0 )) <= state.events_count)
384 if (ret < state.events_count)
386 if ((device = state.devices[ret]) && FAILED( device->vtbl->read( &device->IDirectInputDevice8W_iface ) ))
388 EnterCriticalSection( &dinput_hook_crit );
389 dinput_device_internal_unacquire( &device->IDirectInputDevice8W_iface, STATUS_UNPLUGGED );
390 LeaveCriticalSection( &dinput_hook_crit );
392 state.events[ret] = state.events[--state.events_count];
393 state.devices[ret] = state.devices[state.events_count];
394 state.devices[state.events_count] = state.devices[--state.devices_count];
395 dinput_device_internal_release( device );
399 while (PeekMessageW( &msg, 0, 0, 0, PM_REMOVE ))
401 TranslateMessage(&msg);
402 DispatchMessageW(&msg);
406 if (state.running)
408 ERR( "Unexpected termination, ret %#lx\n", ret );
409 dinput_unacquire_devices();
412 while (state.devices_count--) dinput_device_internal_release( state.devices[state.devices_count] );
413 if (state.keyboard_ll_hook) UnhookWindowsHookEx( state.keyboard_ll_hook );
414 if (state.mouse_ll_hook) UnhookWindowsHookEx( state.mouse_ll_hook );
415 free( state.devices );
416 free( state.events );
418 DestroyWindow( di_em_win );
419 di_em_win = NULL;
420 return 0;
423 void input_thread_start(void)
425 HANDLE start_event;
427 TRACE( "Starting input thread.\n" );
429 if (!(start_event = CreateEventW( NULL, FALSE, FALSE, NULL )))
430 ERR( "Failed to create start event, error %lu\n", GetLastError() );
431 else if (!(dinput_thread = CreateThread( NULL, 0, dinput_thread_proc, start_event, 0, NULL )))
432 ERR( "Failed to create internal thread, error %lu\n", GetLastError() );
433 else
434 WaitForSingleObject( start_event, INFINITE );
436 CloseHandle( start_event );
439 void dinput_hooks_acquire_device( IDirectInputDevice8W *iface )
441 struct dinput_device *impl = impl_from_IDirectInputDevice8W( iface );
443 EnterCriticalSection( &dinput_hook_crit );
444 /* start the input thread now if it wasn't started already */
445 if (!dinput_thread) input_thread_start();
446 list_add_tail( &acquired_device_list, &impl->entry );
447 LeaveCriticalSection( &dinput_hook_crit );
449 SendMessageW( di_em_win, INPUT_THREAD_NOTIFY, NOTIFY_REFRESH_DEVICES, 0 );
452 void dinput_hooks_unacquire_device( IDirectInputDevice8W *iface )
454 struct dinput_device *impl = impl_from_IDirectInputDevice8W( iface );
456 EnterCriticalSection( &dinput_hook_crit );
457 list_remove( &impl->entry );
458 LeaveCriticalSection( &dinput_hook_crit );
460 SendMessageW( di_em_win, INPUT_THREAD_NOTIFY, NOTIFY_REFRESH_DEVICES, 0 );
463 void input_thread_add_user(void)
465 /* we cannot start the input thread here because some games create dinput objects from their DllMain, and
466 * starting the thread will wait for it to initialize, which requires the loader lock to be released.
468 EnterCriticalSection( &dinput_hook_crit );
469 input_thread_user_count++;
470 LeaveCriticalSection( &dinput_hook_crit );
473 void input_thread_remove_user(void)
475 EnterCriticalSection( &dinput_hook_crit );
476 if (!--input_thread_user_count && dinput_thread)
478 TRACE( "Stopping input thread.\n" );
480 SendMessageW( di_em_win, INPUT_THREAD_NOTIFY, NOTIFY_THREAD_STOP, 0 );
481 WaitForSingleObject( dinput_thread, INFINITE );
482 CloseHandle( dinput_thread );
483 dinput_thread = NULL;
485 LeaveCriticalSection( &dinput_hook_crit );
488 void check_dinput_events(void)
490 /* Windows does not do that, but our current implementation of winex11
491 * requires periodic event polling to forward events to the wineserver.
493 * We have to call this function from multiple places, because:
494 * - some games do not explicitly poll for mouse events
495 * (for example Culpa Innata)
496 * - some games only poll the device, and neither keyboard nor mouse
497 * (for example Civilization: Call to Power 2)
498 * - some games do not explicitly poll for keyboard events
499 * (for example Morrowind in its key binding page)
501 MsgWaitForMultipleObjectsEx(0, NULL, 0, QS_ALLINPUT, 0);
504 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, void *reserved )
506 TRACE( "inst %p, reason %lu, reserved %p.\n", inst, reason, reserved );
508 switch(reason)
510 case DLL_PROCESS_ATTACH:
511 DisableThreadLibraryCalls(inst);
512 DINPUT_instance = inst;
513 register_di_em_win_class();
514 break;
515 case DLL_PROCESS_DETACH:
516 if (reserved) break;
517 unregister_di_em_win_class();
518 break;
520 return TRUE;