Debian Codegraph @

Source/Core/InputCommon/ControllerInterface/DInput/DInputKeyboardMouse.cpp

raw symbols SCIP
1 // Copyright 2010 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerInterface/DInput/DInputKeyboardMouse.h"
5
6 #include <algorithm>
7
8 #include "Common/Logging/Log.h"
9
10 #include "Core/Core.h"
11 #include "Core/Host.h"
12
13 #include "InputCommon/ControllerInterface/ControllerInterface.h"
14 #include "InputCommon/ControllerInterface/DInput/DInput.h"
15
16 // (lower would be more sensitive) user can lower sensitivity by setting range
17 // seems decent here ( at 8 ), I don't think anyone would need more sensitive than this
18 // and user can lower it much farther than they would want to with the range
19 #define MOUSE_AXIS_SENSITIVITY 8
20
21 // if input hasn't been received for this many ms, mouse input will be skipped
22 // otherwise it is just some crazy value
23 #define DROP_INPUT_TIME 250
24
25 namespace ciface::DInput
26 {
27 class RelativeMouseAxis final : public Core::Device::RelativeInput
28 {
29 public:
30 std::string GetName() const override
31 {
32 return fmt::format("RelativeMouse {}{}", char('X' + m_index), (m_scale > 0) ? '+' : '-');
33 }
34
35 RelativeMouseAxis(u8 index, bool positive, const RelativeMouseState* state)
36 : m_state(*state), m_index(index), m_scale(positive * 2 - 1)
37 {
38 }
39
40 ControlState GetState() const override
41 {
42 return ControlState(m_state.GetValue().data[m_index] * m_scale);
43 }
44
45 private:
46 const RelativeMouseState& m_state;
47 const u8 m_index;
48 const s8 m_scale;
49 };
50
51 static const struct
52 {
53 const BYTE code;
54 const char* const name;
55 } named_keys[] = {
56 #include "InputCommon/ControllerInterface/DInput/NamedKeys.h" // NOLINT
57 };
58
59 // Prevent duplicate keyboard/mouse devices. Modified by more threads.
60 static bool s_keyboard_mouse_exists;
61 static HWND s_hwnd;
62
63 void InitKeyboardMouse(IDirectInput8* const idi8, HWND hwnd)
64 {
65 if (s_keyboard_mouse_exists)
66 return;
67
68 s_hwnd = hwnd;
69
70 // Mouse and keyboard are a combined device, to allow shift+click and stuff
71 // if that's dumb, I will make a VirtualDevice class that just uses ranges of inputs/outputs from
72 // other devices
73 // so there can be a separated Keyboard and mouse, as well as combined KeyboardMouse
74
75 LPDIRECTINPUTDEVICE8 kb_device = nullptr;
76 LPDIRECTINPUTDEVICE8 mo_device = nullptr;
77
78 // These are "virtual" system devices, so they are always there even if we have no physical
79 // mouse and keyboard plugged into the computer
80 if (SUCCEEDED(idi8->CreateDevice(GUID_SysKeyboard, &kb_device, nullptr)) &&
81 SUCCEEDED(kb_device->SetDataFormat(&c_dfDIKeyboard)) &&
82 SUCCEEDED(kb_device->SetCooperativeLevel(nullptr, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)) &&
83 SUCCEEDED(idi8->CreateDevice(GUID_SysMouse, &mo_device, nullptr)) &&
84 SUCCEEDED(mo_device->SetDataFormat(&c_dfDIMouse2)) &&
85 SUCCEEDED(mo_device->SetCooperativeLevel(nullptr, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)))
86 {
87 g_controller_interface.AddDevice(std::make_shared<KeyboardMouse>(kb_device, mo_device));
88 return;
89 }
90
91 ERROR_LOG_FMT(CONTROLLERINTERFACE, "KeyboardMouse device failed to be created");
92
93 if (kb_device)
94 kb_device->Release();
95 if (mo_device)
96 mo_device->Release();
97 }
98
99 void SetKeyboardMouseWindow(HWND hwnd)
100 {
101 s_hwnd = hwnd;
102 }
103
104 KeyboardMouse::~KeyboardMouse()
105 {
106 s_keyboard_mouse_exists = false;
107
108 // Independently of the order in which we do these, if we put a breakpoint on Unacquire() (or in
109 // any place in the call stack before this), when refreshing devices from the UI, on the second
110 // attempt, it will get stuck in an infinite (while) loop inside dinput8.dll. Given that it can't
111 // be otherwise be reproduced (not even with sleeps), we can just ignore the problem.
112
113 // kb
114 m_kb_device->Unacquire();
115 m_kb_device->Release();
116 // mouse
117 m_mo_device->Unacquire();
118 m_mo_device->Release();
119 }
120
121 KeyboardMouse::KeyboardMouse(const LPDIRECTINPUTDEVICE8 kb_device,
122 const LPDIRECTINPUTDEVICE8 mo_device)
123 : m_kb_device(kb_device), m_mo_device(mo_device), m_last_update(GetTickCount()), m_state_in()
124 {
125 s_keyboard_mouse_exists = true;
126
127 if (FAILED(m_kb_device->Acquire()))
128 WARN_LOG_FMT(CONTROLLERINTERFACE, "Keyboard device failed to acquire. We'll retry later");
129 if (FAILED(m_mo_device->Acquire()))
130 WARN_LOG_FMT(CONTROLLERINTERFACE, "Mouse device failed to acquire. We'll retry later");
131
132 // KEYBOARD
133 // add keys
134 for (u8 i = 0; i < sizeof(named_keys) / sizeof(*named_keys); ++i)
135 AddInput(new Key(i, m_state_in.keyboard[named_keys[i].code]));
136
137 // Add combined left/right modifiers with consistent naming across platforms.
138 AddCombinedInput("Alt", {"LMENU", "RMENU"});
139 AddCombinedInput("Shift", {"LSHIFT", "RSHIFT"});
140 AddCombinedInput("Ctrl", {"LCONTROL", "RCONTROL"});
141
142 // MOUSE
143 DIDEVCAPS mouse_caps = {};
144 mouse_caps.dwSize = sizeof(mouse_caps);
145 m_mo_device->GetCapabilities(&mouse_caps);
146 // mouse buttons
147 // We don't use caps here due to reporting inconsistencies
148 for (u8 i = 0; i < std::size(m_state_in.mouse.rgbButtons); ++i)
149 AddInput(new Button(i, m_state_in.mouse.rgbButtons[i]));
150 // mouse axes
151 for (unsigned int i = 0; i < mouse_caps.dwAxes; ++i)
152 {
153 const LONG& ax = (&m_state_in.mouse.lX)[i];
154
155 // each axis gets a negative and a positive input instance associated with it
156 AddInput(new Axis(i, ax, (2 == i) ? -1 : -MOUSE_AXIS_SENSITIVITY));
157 AddInput(new Axis(i, ax, -(2 == i) ? 1 : MOUSE_AXIS_SENSITIVITY));
158 }
159
160 // cursor, with a hax for-loop
161 for (unsigned int i = 0; i < 4; ++i)
162 AddInput(new Cursor(!!(i & 2), (&m_state_in.cursor.x)[i / 2], !!(i & 1)));
163
164 // Raw relative mouse movement.
165 for (unsigned int i = 0; i != mouse_caps.dwAxes; ++i)
166 {
167 AddInput(new RelativeMouseAxis(i, false, &m_state_in.relative_mouse));
168 AddInput(new RelativeMouseAxis(i, true, &m_state_in.relative_mouse));
169 }
170 }
171
172 void KeyboardMouse::UpdateCursorInput()
173 {
174 // Get the size of the current window (in my case Rect.top and Rect.left was zero).
175 RECT rect;
176 GetClientRect(s_hwnd, &rect);
177
178 // Width and height are the size of the rendering window. They could be 0
179 const auto win_width = std::max(rect.right - rect.left, 1l);
180 const auto win_height = std::max(rect.bottom - rect.top, 1l);
181
182 POINT point = {};
183 if (g_controller_interface.IsMouseCenteringRequested() &&
184 (Host_RendererHasFocus() || Host_TASInputHasFocus()))
185 {
186 point.x = win_width / 2;
187 point.y = win_height / 2;
188
189 POINT screen_point = point;
190 ClientToScreen(s_hwnd, &screen_point);
191 SetCursorPos(screen_point.x, screen_point.y);
192 g_controller_interface.SetMouseCenteringRequested(false);
193 }
194 else if (Host_TASInputHasFocus())
195 {
196 // When a TAS Input window has focus and "Enable Controller Input" is checked most types of
197 // input should be read normally as if the render window had focus instead. The cursor is an
198 // exception, as otherwise using the mouse to set any control in the TAS Input window will also
199 // update the Wii IR value (or any other input controlled by the cursor).
200
201 return;
202 }
203 else
204 {
205 GetCursorPos(&point);
206
207 // Get the cursor position relative to the upper left corner of the current window
208 // (separate or render to main)
209 ScreenToClient(s_hwnd, &point);
210 }
211
212 const auto window_scale = g_controller_interface.GetWindowInputScale();
213
214 // Convert the cursor position to a range from -1 to 1.
215 m_state_in.cursor.x = (ControlState(point.x) / win_width * 2 - 1) * window_scale.x;
216 m_state_in.cursor.y = (ControlState(point.y) / win_height * 2 - 1) * window_scale.y;
217 }
218
219 Core::DeviceRemoval KeyboardMouse::UpdateInput()
220 {
221 UpdateCursorInput();
222
223 DIMOUSESTATE2 tmp_mouse;
224
225 // if mouse position hasn't been updated in a short while, skip a dev state
226 DWORD cur_time = GetTickCount();
227 if (cur_time - m_last_update > DROP_INPUT_TIME)
228 {
229 // set axes to zero
230 m_state_in.mouse = {};
231 m_state_in.relative_mouse = {};
232
233 // skip this input state
234 m_mo_device->GetDeviceState(sizeof(tmp_mouse), &tmp_mouse);
235 }
236
237 m_last_update = cur_time;
238
239 HRESULT mo_hr = m_mo_device->GetDeviceState(sizeof(tmp_mouse), &tmp_mouse);
240 if (DIERR_INPUTLOST == mo_hr || DIERR_NOTACQUIRED == mo_hr)
241 {
242 INFO_LOG_FMT(CONTROLLERINTERFACE, "Mouse device failed to get state");
243 if (FAILED(m_mo_device->Acquire()))
244 INFO_LOG_FMT(CONTROLLERINTERFACE, "Mouse device failed to re-acquire, we'll retry later");
245 }
246 else if (SUCCEEDED(mo_hr))
247 {
248 m_state_in.relative_mouse.Move({tmp_mouse.lX, tmp_mouse.lY, tmp_mouse.lZ});
249 m_state_in.relative_mouse.Update();
250
251 // need to smooth out the axes, otherwise it doesn't work for shit
252 for (unsigned int i = 0; i < 3; ++i)
253 ((&m_state_in.mouse.lX)[i] += (&tmp_mouse.lX)[i]) /= 2;
254
255 // copy over the buttons
256 std::copy_n(tmp_mouse.rgbButtons, std::size(tmp_mouse.rgbButtons), m_state_in.mouse.rgbButtons);
257 }
258
259 HRESULT kb_hr = m_kb_device->GetDeviceState(sizeof(m_state_in.keyboard), &m_state_in.keyboard);
260 if (kb_hr == DIERR_INPUTLOST || kb_hr == DIERR_NOTACQUIRED)
261 {
262 INFO_LOG_FMT(CONTROLLERINTERFACE, "Keyboard device failed to get state");
263 if (SUCCEEDED(m_kb_device->Acquire()))
264 m_kb_device->GetDeviceState(sizeof(m_state_in.keyboard), &m_state_in.keyboard);
265 else
266 INFO_LOG_FMT(CONTROLLERINTERFACE, "Keyboard device failed to re-acquire, we'll retry later");
267 }
268
269 return Core::DeviceRemoval::Keep;
270 }
271
272 std::string KeyboardMouse::GetName() const
273 {
274 return "Keyboard Mouse";
275 }
276
277 std::string KeyboardMouse::GetSource() const
278 {
279 return DINPUT_SOURCE_NAME;
280 }
281
282 // Give this device a higher priority to make sure it shows first
283 int KeyboardMouse::GetSortPriority() const
284 {
285 return DEFAULT_DEVICE_SORT_PRIORITY;
286 }
287
288 bool KeyboardMouse::IsVirtualDevice() const
289 {
290 return true;
291 }
292
293 // names
294 std::string KeyboardMouse::Key::GetName() const
295 {
296 return named_keys[m_index].name;
297 }
298
299 std::string KeyboardMouse::Button::GetName() const
300 {
301 return std::string("Click ") + char('0' + m_index);
302 }
303
304 std::string KeyboardMouse::Axis::GetName() const
305 {
306 char tmpstr[] = "Axis ..";
307 tmpstr[5] = (char)('X' + m_index);
308 tmpstr[6] = (m_range < 0 ? '-' : '+');
309 return tmpstr;
310 }
311
312 std::string KeyboardMouse::Cursor::GetName() const
313 {
314 char tmpstr[] = "Cursor ..";
315 tmpstr[7] = (char)('X' + m_index);
316 tmpstr[8] = (m_positive ? '+' : '-');
317 return tmpstr;
318 }
319
320 // get/set state
321 ControlState KeyboardMouse::Key::GetState() const
322 {
323 return (m_key != 0);
324 }
325
326 ControlState KeyboardMouse::Button::GetState() const
327 {
328 return (m_button != 0);
329 }
330
331 ControlState KeyboardMouse::Axis::GetState() const
332 {
333 return ControlState(m_axis) / m_range;
334 }
335
336 ControlState KeyboardMouse::Cursor::GetState() const
337 {
338 return m_axis / (m_positive ? 1.0 : -1.0);
339 }
340 } // namespace ciface::DInput