swift
Loading...
Searching...
No Matches
joystickwindows.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2014 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
4#include "joystickwindows.h"
5
6#include "Dbt.h"
7#include "comdef.h"
8
9#include "misc/logmessage.h"
10#include "misc/metadatautils.h"
11
12// Qt5 defines UNICODE, hence we can expect an wchar_t strings.
13// If it fails to compile, because of char/wchar_t errors, you are most likely
14// using ascii functions of WINAPI. To fix it, introduce #ifdef UNICODE and add char
15// handling in the second branch.
16
17using namespace swift::misc;
18using namespace swift::misc::input;
19
20namespace swift::input
21{
22 CJoystickDevice::CJoystickDevice(DirectInput8Ptr directInputPtr, const DIDEVICEINSTANCE *pdidInstance,
24 : QObject(parent), m_guidDevice(pdidInstance->guidInstance), m_guidProduct(pdidInstance->guidProduct),
25 m_deviceName(QString::fromWCharArray(pdidInstance->tszInstanceName).simplified()),
26 m_productName(QString::fromWCharArray(pdidInstance->tszProductName).simplified()),
27 m_directInput(directInputPtr)
28 {
29 this->setObjectName(classNameShort(this));
30 }
31
32 bool CJoystickDevice::init(HWND helperWindow)
33 {
34 HRESULT hr;
35 // Create device
36 {
37 IDirectInputDevice8 *diDevice = nullptr;
38 if (FAILED(hr = m_directInput->CreateDevice(m_guidDevice, &diDevice, nullptr)))
39 {
40 CLogMessage(this).warning(u"IDirectInput8::CreateDevice failed: ") << hr;
41 return false;
42 }
43 m_directInputDevice.reset(diDevice);
44 }
45
46 // Set cooperative level
47 if (!helperWindow)
48 {
49 return false;
50 }
51 if (FAILED(hr = m_directInputDevice->SetCooperativeLevel(helperWindow, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND)))
52 {
53 CLogMessage(this).warning(u"IDirectInputDevice8::SetCooperativeLevel failed: ") << hr;
54 return false;
55 }
56
57 // Set data format to c_dfDIJoystick2
58 if (FAILED(hr = m_directInputDevice->SetDataFormat(&c_dfDIJoystick2)))
59 {
60 CLogMessage(this).warning(u"IDirectInputDevice8::SetDataFormat failed: ") << hr;
61 return false;
62 }
63
64 DIDEVCAPS deviceCaps;
65 deviceCaps.dwSize = sizeof(DIDEVCAPS);
66 // Get device capabilities - we are interested in the number of buttons.
67 if (FAILED(hr = m_directInputDevice->GetCapabilities(&deviceCaps)))
68 {
69 CLogMessage(this).warning(u"IDirectInputDevice8::GetCapabilities failed: ") << hr;
70 return false;
71 }
72
73 // Filter devices with 0 buttons
74 if (deviceCaps.dwButtons == 0)
75 {
76 return false;
77 }
78
79 // fix for the toggle button issue T585
80 // if (FAILED(hr = m_directInputDevice->EnumObjects(enumObjectsCallback, this, DIDFT_BUTTON)))
81 if (FAILED(hr = m_directInputDevice->EnumObjects(enumObjectsCallback, this, DIDFT_PSHBUTTON)))
82 {
83 CLogMessage(this).warning(u"IDirectInputDevice8::EnumObjects failed: ") << hr;
84 return false;
85 }
86
87 CLogMessage(this).info(u"Created joystick device '%1' with %2 buttons") << m_deviceName << deviceCaps.dwButtons;
88 this->startTimer(50);
89 return true;
90 }
91
93 {
94 CJoystickButtonList buttons;
95 for (const CJoystickDeviceInput &deviceInput : m_joystickDeviceInputs)
96 {
97 buttons.push_back(deviceInput.m_button);
98 }
99 return buttons;
100 }
101
103 {
104 Q_UNUSED(event)
105 pollDeviceState();
106 }
107
108 HRESULT CJoystickDevice::pollDeviceState()
109 {
110 m_directInputDevice->Poll();
111
112 DIJOYSTATE2 state;
113 HRESULT hr = m_directInputDevice->GetDeviceState(sizeof(DIJOYSTATE2), &state);
114 if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED)
115 {
116 m_directInputDevice->Acquire();
117 m_directInputDevice->Poll();
118 hr = m_directInputDevice->GetDeviceState(sizeof(DIJOYSTATE2), &state);
119 }
120
121 if (FAILED(hr))
122 {
123 CLogMessage(this).warning(u"Cannot acquire and poll joystick device %1. Removing it.") << m_deviceName;
124 emit connectionLost(m_guidDevice);
125 return hr;
126 }
127
128 for (const CJoystickDeviceInput &input : std::as_const(m_joystickDeviceInputs))
129 {
130 const qint32 buttonIndex = input.m_offset - DIJOFS_BUTTON0;
131 const bool isPressed = state.rgbButtons[buttonIndex] & 0x80;
132 emit this->buttonChanged(input.m_button, isPressed);
133 }
134 return hr;
135 }
136
137 QString CJoystickDevice::hrString(HRESULT hr)
138 {
139 // https://stackoverflow.com/questions/7008047/is-there-a-way-to-get-the-string-representation-of-hresult-value-using-win-api
140 _com_error err(hr);
141 LPCTSTR errMsg = err.ErrorMessage();
142 return QString::fromWCharArray(errMsg);
143 }
144
145 BOOL CALLBACK CJoystickDevice::enumObjectsCallback(const DIDEVICEOBJECTINSTANCE *dev, LPVOID pvRef)
146 {
147 CJoystickDevice *joystickDevice = static_cast<CJoystickDevice *>(pvRef);
148
149 // Make sure we only got GUID_Button types
150 if (dev->guidType != GUID_Button) return DIENUM_CONTINUE;
151
152 CJoystickDeviceInput deviceInput;
153 const int number = joystickDevice->m_joystickDeviceInputs.size();
154 deviceInput.m_offset = DIJOFS_BUTTON(number);
155 deviceInput.m_button = CJoystickButton(joystickDevice->m_deviceName, DIJOFS_BUTTON(number) - DIJOFS_BUTTON0);
156
157 joystickDevice->m_joystickDeviceInputs.append(deviceInput);
158 CLogMessage(static_cast<CJoystickWindows *>(nullptr)).debug()
159 << "Found joystick button" << QString::fromWCharArray(dev->tszName) << joystickDevice->m_deviceName;
160
161 return DIENUM_CONTINUE;
162 }
163
164 CJoystickWindows::CJoystickWindows(QObject *parent) : IJoystick(parent)
165 {
166 // Initialize COM.
167 // https://docs.microsoft.com/en-us/windows/desktop/api/combaseapi/nf-combaseapi-coinitializeex
168 HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
169
170 // RPC_E_CHANGED_MODE: CoInitializeEx was already called by someone else in this thread with a different mode.
171 if (hr == RPC_E_CHANGED_MODE)
172 {
173 CLogMessage(this).debug(u"CoInitializeEx was already called with a different mode. Trying again.");
174 hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
175 }
176
177 // Continue here only if CoInitializeEx was successful
178 // S_OK: The COM library was initialized successfully on this thread.
179 // S_FALSE: The COM library is already initialized on this thread. Reference count was incremented. This is not
180 // an error.
181 if (hr == S_OK || hr == S_FALSE)
182 {
183 m_coInitializeSucceeded = true;
184 this->createHelperWindow();
185
186 if (helperWindow)
187 {
188 this->initDirectInput();
189 this->enumJoystickDevices();
190 this->requestDeviceNotification();
191 }
192 }
193 else
194 {
195 CLogMessage(this).warning(u"CoInitializeEx returned error code %1");
196 }
197 }
198
200 {
201 // All DirectInput devices need to be cleaned up before the call to CoUninitialize()
202 for (CJoystickDevice *joystickDevice : std::as_const(m_joystickDevices))
203 {
204 delete joystickDevice;
205 }
206 m_joystickDevices.clear();
207 m_directInput.reset();
208 if (m_coInitializeSucceeded)
209 {
210 CoUninitialize();
211 }
212 if (hDevNotify)
213 {
214 UnregisterDeviceNotification(hDevNotify);
215 }
216 destroyHelperWindow();
217 }
218
220 {
221 CJoystickButtonList availableButtons;
222 for (const CJoystickDevice *device : std::as_const(m_joystickDevices))
223 {
224 availableButtons.push_back(device->getDeviceButtons());
225 }
226 return availableButtons;
227 }
228
229 void ReleaseDirectInput(IDirectInput8 *obj)
230 {
231 if (obj)
232 {
233 obj->Release();
234 }
235 }
236
237 HRESULT CJoystickWindows::initDirectInput()
238 {
239 IDirectInput8 *directInput = nullptr;
240 // HRESULT hr = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8,
241 // reinterpret_cast<LPVOID *>(&directInput), nullptr);
242 HRESULT hr = CoCreateInstance(CLSID_DirectInput8, nullptr, CLSCTX_INPROC_SERVER, IID_IDirectInput8,
243 reinterpret_cast<LPVOID *>(&directInput));
244 if (FAILED(hr))
245 {
246 return hr;
247 }
248 m_directInput = DirectInput8Ptr(directInput, ReleaseDirectInput);
249
250 HINSTANCE instance = GetModuleHandle(nullptr);
251 hr = m_directInput->Initialize(instance, DIRECTINPUT_VERSION);
252 return hr;
253 }
254
255 HRESULT CJoystickWindows::enumJoystickDevices()
256 {
257 if (!m_directInput)
258 {
259 CLogMessage(this).warning(u"No direct input");
260 return E_FAIL;
261 }
262
263 HRESULT hr;
264 if (FAILED(hr = m_directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, enumJoysticksCallback, this,
265 DIEDFL_ATTACHEDONLY)))
266 {
267 CLogMessage(this).error(u"Error reading joystick devices");
268 return hr;
269 }
270
271 if (m_joystickDevices.isEmpty())
272 {
273 CLogMessage(this).info(u"No joystick device found");
274 }
275 return hr;
276 }
277
278 int CJoystickWindows::createHelperWindow()
279 {
280 // Make sure window isn't created twice
281 if (helperWindow != nullptr)
282 {
283 return 0;
284 }
285
286 HINSTANCE hInstance = GetModuleHandle(nullptr);
287 WNDCLASSEX wce;
288 ZeroMemory(&wce, sizeof(wce));
289 wce.cbSize = sizeof(wce);
290 wce.lpfnWndProc = windowProc;
291 wce.lpszClassName = static_cast<LPCWSTR>(helperWindowClassName);
292 wce.hInstance = hInstance;
293
294 /* Register the class. */
295 if (!RegisterClassEx(&wce))
296 {
297 return -1;
298 }
299
300 /* Create the window. */
301 helperWindow =
302 CreateWindowEx(0, helperWindowClassName, helperWindowName, WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT,
303 CW_USEDEFAULT, CW_USEDEFAULT, HWND_MESSAGE, nullptr, hInstance, nullptr);
304 if (helperWindow == nullptr)
305 {
306 UnregisterClass(helperWindowClassName, hInstance);
307 return -1;
308 }
309
310 SetProp(helperWindow, L"CJoystickWindows", this);
311
312 return 0;
313 }
314
315 void CJoystickWindows::requestDeviceNotification()
316 {
317 DEV_BROADCAST_DEVICEINTERFACE notificationFilter;
318 ZeroMemory(&notificationFilter, sizeof(notificationFilter));
319 notificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
320 notificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
321 hDevNotify = RegisterDeviceNotification(helperWindow, &notificationFilter,
322 DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
323 }
324
325 void CJoystickWindows::destroyHelperWindow()
326 {
327 HINSTANCE hInstance = GetModuleHandle(nullptr);
328
329 if (helperWindow == nullptr)
330 {
331 return;
332 }
333
334 DestroyWindow(helperWindow);
335 helperWindow = nullptr;
336
337 UnregisterClass(helperWindowClassName, hInstance);
338 }
339
340 void CJoystickWindows::addJoystickDevice(const DIDEVICEINSTANCE *pdidInstance)
341 {
342 CJoystickDevice *device = new CJoystickDevice(m_directInput, pdidInstance, this);
343 bool success = device->init(helperWindow);
344 if (success)
345 {
346 connect(device, &CJoystickDevice::buttonChanged, this, &CJoystickWindows::joystickButtonChanged);
347 connect(device, &CJoystickDevice::connectionLost, this, &CJoystickWindows::removeJoystickDevice);
348 m_joystickDevices.push_back(device);
349 }
350 else
351 {
352 delete device;
353 }
354 }
355
356 bool CJoystickWindows::isJoystickAlreadyAdded(const DIDEVICEINSTANCE *pdidInstance) const
357 {
358 for (const CJoystickDevice *device : m_joystickDevices)
359 {
360 if (IsEqualGUID(device->getDeviceGuid(), pdidInstance->guidInstance))
361 {
362 return true;
363 }
364 }
365
366 return false;
367 }
368
369 void CJoystickWindows::joystickButtonChanged(const CJoystickButton &joystickButton, bool isPressed)
370 {
371 CHotkeyCombination oldCombination(m_buttonCombination);
372 if (isPressed)
373 {
374 m_buttonCombination.addJoystickButton(joystickButton);
375 }
376 else
377 {
378 m_buttonCombination.removeJoystickButton(joystickButton);
379 }
380
381 if (oldCombination != m_buttonCombination)
382 {
383 emit buttonCombinationChanged(m_buttonCombination);
384 }
385 }
386
387 void CJoystickWindows::removeJoystickDevice(const GUID &guid)
388 {
389 for (auto it = m_joystickDevices.begin(); it != m_joystickDevices.end(); ++it)
390 {
391 CJoystickDevice *device = *it;
392 if (IsEqualGUID(guid, device->getDeviceGuid()))
393 {
394 device->deleteLater();
395 m_joystickDevices.erase(it);
396 break;
397 }
398 }
399 }
400
401 //
402 // Window callback function (handles window messages)
403 //
404 LRESULT CALLBACK CJoystickWindows::windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
405 {
406 CJoystickWindows *joystickWindows = static_cast<CJoystickWindows *>(GetProp(hWnd, L"CJoystickWindows"));
407
408 if (joystickWindows)
409 {
410 switch (uMsg)
411 {
412 case WM_DEVICECHANGE:
413 {
414 if (wParam == DBT_DEVICEARRIVAL)
415 {
416 const DEV_BROADCAST_HDR *dbh = reinterpret_cast<DEV_BROADCAST_HDR *>(lParam);
417 // DEV_BROADCAST_HDR *dbh = (DEV_BROADCAST_HDR *) lParam;
418 if (dbh && dbh->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
419 {
420 joystickWindows->enumJoystickDevices();
421 }
422 }
423 }
424 }
425 }
426
427 return DefWindowProc(hWnd, uMsg, wParam, lParam);
428 }
429
430 BOOL CALLBACK CJoystickWindows::enumJoysticksCallback(const DIDEVICEINSTANCE *pdidInstance, VOID *pContext)
431 {
432 CJoystickWindows *obj = static_cast<CJoystickWindows *>(pContext);
433
434 /* ignore XInput devices here, keep going. */
435 // if (isXInputDevice(&pdidInstance->guidProduct)) return DIENUM_CONTINUE;
436
437 if (!obj->isJoystickAlreadyAdded(pdidInstance))
438 {
439 obj->addJoystickDevice(pdidInstance);
440 CLogMessage(static_cast<CJoystickWindows *>(nullptr)).debug()
441 << "Found joystick device" << QString::fromWCharArray(pdidInstance->tszInstanceName);
442 }
443 return DIENUM_CONTINUE;
444 }
445
446 bool operator==(const CJoystickDevice &lhs, const CJoystickDevice &rhs)
447 {
448 return lhs.m_guidDevice == rhs.m_guidDevice && lhs.m_guidProduct == rhs.m_guidProduct &&
449 lhs.m_deviceName == rhs.m_deviceName && lhs.m_productName == rhs.m_productName;
450 }
451
452 bool operator==(CJoystickDeviceInput const &lhs, CJoystickDeviceInput const &rhs)
453 {
454 return lhs.m_offset == rhs.m_offset && lhs.m_button == rhs.m_button;
455 }
456} // namespace swift::input
Linux Joystick device.
bool init(const IOHIDDeviceRef device)
Initialize device.
void connectionLost(const GUID &guid)
Connection to joystick lost. Probably unplugged.
friend bool operator==(const CJoystickDevice &lhs, const CJoystickDevice &rhs)
Equal operator.
void buttonChanged(const QString &name, int index, bool isPressed)
Joystick button changed.
virtual void timerEvent(QTimerEvent *event)
Timer based updates.
swift::misc::input::CJoystickButtonList getDeviceButtons() const
Get all available device buttons.
CJoystickDevice(const QString &path, QFile *fd, QObject *parent)
Constructor.
virtual ~CJoystickWindows()
Destructor.
virtual swift::misc::input::CJoystickButtonList getAllAvailableJoystickButtons() const
Get all available joystick buttons.
CJoystickWindows(CJoystickWindows const &)=delete
Copy Constructor.
Abstract interface for native joystick handling.
Definition joystick.h:22
void buttonCombinationChanged(const swift::misc::input::CHotkeyCombination &)
Joystick button combination has changed.
Class for emitting a log message.
Definition logmessage.h:27
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
void push_back(const T &value)
Appends an element at the end of the sequence.
Definition sequence.h:308
Value object encapsulating a list of joystick buttons.
std::shared_ptr< IDirectInput8 > DirectInput8Ptr
Shared IDirectInput8 ptr.
Free functions in swift::misc.
QString classNameShort(const QObject *object)
Class name as from QMetaObject::className without namespace.
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
virtual bool event(QEvent *e)
QObject * parent() const const
void setObjectName(QAnyStringView name)
int startTimer(int interval, Qt::TimerType timerType)
QString fromWCharArray(const wchar_t *string, qsizetype size)
Joystick device input/button.
swift::misc::input::CJoystickButton m_button
Joystick button.