Debian Codegraph @

Source/Core/InputCommon/ControllerInterface/Xlib/XInput2.cpp

raw symbols SCIP
1 // Copyright 2013 Max Eliaser
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerInterface/Xlib/XInput2.h"
5
6 #include <X11/XKBlib.h>
7 #include <X11/extensions/XInput2.h>
8
9 #include <algorithm>
10 #include <cstdlib>
11 #include <cstring>
12 #include <map>
13
14 #include <fmt/format.h>
15
16 #include "Common/Logging/Log.h"
17
18 #include "Core/Host.h"
19
20 // This is an input plugin using the XInput 2.0 extension to the X11 protocol,
21 // loosely based on the old XLib plugin. (Has nothing to do with the XInput
22 // API on Windows.)
23
24 // This plugin creates one KeyboardMouse object for each master pointer/
25 // keyboard pair. Each KeyboardMouse object exports four types of controls:
26 // * Mouse button controls: hardcoded at 32 of them, but could be made to
27 // support infinitely many mouse buttons in theory; XInput2 has no limit.
28 // * Mouse cursor controls: one for each cardinal direction. Calculated by
29 // comparing the absolute position of the mouse pointer on screen to the
30 // center of the emulator window.
31 // * Mouse axis controls: one for each cardinal direction. Calculated using
32 // a running average of relative mouse motion on each axis.
33 // * Key controls: these correspond to a limited subset of the keyboard
34 // keys.
35
36 // Mouse axis control tuning. Unlike absolute mouse position, relative mouse
37 // motion data needs to be tweaked and smoothed out a bit to be usable.
38
39 // Mouse axis control output is simply divided by this number. In practice,
40 // that just means you can use a smaller "dead zone" if you bind axis controls
41 // to a joystick. No real need to make this customizable.
42 #define MOUSE_AXIS_SENSITIVITY 8.0f
43
44 // The mouse axis controls use a weighted running average. Each frame, the new
45 // value is the average of the old value and the amount of relative mouse
46 // motion during that frame. The old value is weighted by a ratio of
47 // MOUSE_AXIS_SMOOTHING:1 compared to the new value. Increasing
48 // MOUSE_AXIS_SMOOTHING makes the controls smoother, decreasing it makes them
49 // more responsive. This might be useful as a user-customizable option.
50 #define MOUSE_AXIS_SMOOTHING 1.5f
51
52 // The scroll axis value should decay a lot faster than the mouse axes since
53 // it should ideally register each click of the scroll wheel. Decreasing this
54 // value makes it more likely that a scroll wheel input is registered, but less
55 // likely to differentiate between different inputs, while increasing it will
56 // more cleanly separate each scroll wheel click, but risks dropping some inputs
57 #define SCROLL_AXIS_DECAY 1.1f
58
59 namespace
60 {
61 // We need XInput 2.1 to get raw events on the root window even while another
62 // client has a grab. If we request 2.2 or later, the server will not generate
63 // emulated button presses from touch events, so we want exactly 2.1.
64 constexpr int XINPUT_MAJOR = 2, XINPUT_MINOR = 1;
65 } // namespace
66
67 namespace ciface::XInput2
68 {
69 constexpr std::string_view SOURCE_NAME = "XInput2";
70
71 class InputBackend final : public ciface::InputBackend
72 {
73 public:
74 using ciface::InputBackend::InputBackend;
75 void PopulateDevices() override;
76 void HandleWindowChange() override;
77 };
78
79 std::unique_ptr<ciface::InputBackend> CreateInputBackend(ControllerInterface* controller_interface)
80 {
81 return std::make_unique<InputBackend>(controller_interface);
82 }
83
84 void InputBackend::HandleWindowChange()
85 {
86 GetControllerInterface().RemoveDevice(
87 [](const auto* dev) { return dev->GetSource() == SOURCE_NAME; }, true);
88
89 PopulateDevices();
90 }
91
92 // This function will add zero or more KeyboardMouse objects to devices.
93 void InputBackend::PopulateDevices()
94 {
95 const WindowSystemInfo wsi = GetControllerInterface().GetWindowSystemInfo();
96 if (wsi.type != WindowSystemType::X11)
97 return;
98
99 const auto hwnd = wsi.render_window;
100
101 Display* dpy = XOpenDisplay(nullptr);
102
103 // xi_opcode is important; it will be used to identify XInput events by
104 // the polling loop in UpdateInput.
105 int xi_opcode, event, error;
106
107 // verify that the XInput extension is available
108 if (!XQueryExtension(dpy, "XInputExtension", &xi_opcode, &event, &error))
109 {
110 WARN_LOG_FMT(CONTROLLERINTERFACE, "XInput extension not available (XQueryExtension)");
111 return;
112 }
113
114 int major = XINPUT_MAJOR, minor = XINPUT_MINOR;
115 if (XIQueryVersion(dpy, &major, &minor) != Success || major < XINPUT_MAJOR ||
116 (major == XINPUT_MAJOR && minor < XINPUT_MINOR))
117 {
118 WARN_LOG_FMT(CONTROLLERINTERFACE, "XInput extension not available (XIQueryVersion)");
119 return;
120 }
121
122 // register all master devices with Dolphin
123
124 XIDeviceInfo* all_masters;
125 XIDeviceInfo* current_master;
126 double scroll_increment = 1.0f;
127 int num_masters;
128
129 all_masters = XIQueryDevice(dpy, XIAllMasterDevices, &num_masters);
130
131 for (int i = 0; i < num_masters; i++)
132 {
133 current_master = &all_masters[i];
134
135 if (current_master->use == XIMasterPointer)
136 {
137 // We need to query the master for the scroll wheel's increment, since the increment used
138 // varies depending on what input driver is being used. For example, xf86-libinput uses 120.0.
139 for (int j = 0; j < current_master->num_classes; j++)
140 {
141 if (current_master->classes[j]->type == XIScrollClass)
142 {
143 XIScrollClassInfo* scroll_event =
144 reinterpret_cast<XIScrollClassInfo*>(current_master->classes[j]);
145 scroll_increment = scroll_event->increment;
146 break;
147 }
148 }
149 // Since current_master is a master pointer, its attachment must
150 // be a master keyboard.
151 GetControllerInterface().AddDevice(
152 std::make_shared<KeyboardMouse>((Window)hwnd, xi_opcode, current_master->deviceid,
153 current_master->attachment, scroll_increment));
154 }
155 }
156
157 XCloseDisplay(dpy);
158
159 XIFreeDeviceInfo(all_masters);
160 }
161
162 KeyboardMouse::KeyboardMouse(Window window, int opcode, int pointer, int keyboard,
163 double scroll_increment_)
164 : m_window(window), xi_opcode(opcode), pointer_deviceid(pointer), keyboard_deviceid(keyboard),
165 scroll_increment(scroll_increment_)
166 {
167 // The cool thing about each KeyboardMouse object having its own Display
168 // is that each one gets its own separate copy of the X11 event stream,
169 // which it can individually filter to get just the events it's interested
170 // in. So be aware that each KeyboardMouse object actually has its own X11
171 // "context."
172 m_display = XOpenDisplay(nullptr);
173
174 int major = XINPUT_MAJOR, minor = XINPUT_MINOR;
175 XIQueryVersion(m_display, &major, &minor);
176
177 // should always be 1
178 int unused;
179 XIDeviceInfo* const pointer_device = XIQueryDevice(m_display, pointer_deviceid, &unused);
180 name = std::string(pointer_device->name);
181 XIFreeDeviceInfo(pointer_device);
182
183 // Tell core X functions which keyboard is "the" keyboard for this
184 // X connection.
185 XISetClientPointer(m_display, None, pointer_deviceid);
186
187 {
188 unsigned char mask_buf[(XI_LASTEVENT + 7) / 8] = {};
189 XISetMask(mask_buf, XI_RawButtonPress);
190 XISetMask(mask_buf, XI_RawButtonRelease);
191 XISetMask(mask_buf, XI_RawMotion);
192
193 XIEventMask mask;
194 mask.mask = mask_buf;
195 mask.mask_len = sizeof(mask_buf);
196
197 mask.deviceid = pointer_deviceid;
198 XISelectEvents(m_display, DefaultRootWindow(m_display), &mask, 1);
199 }
200
201 {
202 unsigned char mask_buf[(XI_LASTEVENT + 7) / 8] = {};
203 XISetMask(mask_buf, XI_RawKeyPress);
204 XISetMask(mask_buf, XI_RawKeyRelease);
205
206 XIEventMask mask;
207 mask.mask = mask_buf;
208 mask.mask_len = sizeof(mask_buf);
209 mask.deviceid = keyboard_deviceid;
210 XISelectEvents(m_display, DefaultRootWindow(m_display), &mask, 1);
211 }
212
213 // Temporary map to combine keycodes with the same name.
214 std::map<std::string, Key*> keys;
215
216 // Keyboard Keys
217 int min_keycode = 0;
218 int max_keycode = 0;
219 XDisplayKeycodes(m_display, &min_keycode, &max_keycode);
220 for (int keycode = min_keycode; keycode <= max_keycode; ++keycode)
221 {
222 const auto* const keycode_name = Key::GetNameForKeyCode(m_display, keycode);
223 if (keycode_name == nullptr)
224 continue;
225
226 auto& key_input = keys[keycode_name];
227 if (key_input == nullptr)
228 AddInput(key_input = new Key(keycode_name, keycode, m_state.keyboard.data()));
229 else
230 key_input->AddKeyCode(keycode);
231 }
232
233 // Add combined left/right modifiers with consistent naming across platforms.
234 AddCombinedInput("Alt", {"Alt_L", "Alt_R"});
235 AddCombinedInput("Shift", {"Shift_L", "Shift_R"});
236 AddCombinedInput("Ctrl", {"Control_L", "Control_R"});
237
238 // Mouse Buttons
239 for (int i = 0; i < 32; i++)
240 AddInput(new Button(i, &m_state.buttons));
241
242 // Mouse Cursor, X-/+ and Y-/+
243 for (int i = 0; i != 4; ++i)
244 AddInput(new Cursor(!!(i & 2), !!(i & 1), (i & 2) ? &m_state.cursor.y : &m_state.cursor.x));
245
246 // Mouse Axis, X-/+, Y-/+ and Z-/+
247 AddInput(new Axis(0, false, &m_state.axis.x));
248 AddInput(new Axis(0, true, &m_state.axis.x));
249 AddInput(new Axis(1, false, &m_state.axis.y));
250 AddInput(new Axis(1, true, &m_state.axis.y));
251 AddInput(new Axis(2, false, &m_state.axis.z));
252 AddInput(new Axis(2, true, &m_state.axis.z));
253
254 // Relative Mouse, X-/+, Y-/+ and Z-/+
255 AddInput(new RelativeMouse(0, false, &m_state.relative_mouse.x));
256 AddInput(new RelativeMouse(0, true, &m_state.relative_mouse.x));
257 AddInput(new RelativeMouse(1, false, &m_state.relative_mouse.y));
258 AddInput(new RelativeMouse(1, true, &m_state.relative_mouse.y));
259 AddInput(new RelativeMouse(2, false, &m_state.relative_mouse.z));
260 AddInput(new RelativeMouse(2, true, &m_state.relative_mouse.z));
261 }
262
263 KeyboardMouse::~KeyboardMouse()
264 {
265 XCloseDisplay(m_display);
266 }
267
268 // Update the mouse cursor controls
269 void KeyboardMouse::UpdateCursor(bool should_center_mouse)
270 {
271 double root_x, root_y, win_x, win_y;
272 Window root, child;
273
274 XWindowAttributes win_attribs;
275 XGetWindowAttributes(m_display, m_window, &win_attribs);
276 const auto win_width = std::max(win_attribs.width, 1);
277 const auto win_height = std::max(win_attribs.height, 1);
278
279 {
280 XIButtonState button_state;
281 XIModifierState mods;
282 XIGroupState group;
283
284 // Get the absolute position of the mouse pointer and the button state.
285 XIQueryPointer(m_display, pointer_deviceid, m_window, &root, &child, &root_x, &root_y, &win_x,
286 &win_y, &button_state, &mods, &group);
287
288 // X buttons are 1-indexed, so to get 32 button bits we need a larger type
289 // for the shift.
290 u64 buttons_zero_indexed = 0;
291 std::memcpy(&buttons_zero_indexed, button_state.mask,
292 std::min<size_t>(button_state.mask_len, sizeof(m_state.buttons)));
293 m_state.buttons = buttons_zero_indexed >> 1;
294
295 free(button_state.mask);
296 }
297
298 if (should_center_mouse)
299 {
300 win_x = win_width / 2;
301 win_y = win_height / 2;
302
303 XIWarpPointer(m_display, pointer_deviceid, None, m_window, 0.0, 0.0, 0, 0, win_x, win_y);
304
305 g_controller_interface.SetMouseCenteringRequested(false);
306 }
307
308 const auto window_scale = g_controller_interface.GetWindowInputScale();
309
310 // the mouse position as a range from -1 to 1
311 m_state.cursor.x = (win_x / win_width * 2 - 1) * window_scale.x;
312 m_state.cursor.y = (win_y / win_height * 2 - 1) * window_scale.y;
313 }
314
315 Core::DeviceRemoval KeyboardMouse::UpdateInput()
316 {
317 XFlush(m_display);
318
319 // for the axis controls
320 float delta_x = 0.0f, delta_y = 0.0f, delta_z = 0.0f;
321 double delta_delta;
322 bool update_mouse = false, update_keyboard = false;
323
324 // Iterate through the event queue, processing raw pointer motion events and
325 // noting whether the button or key state has changed.
326 XEvent event;
327 while (XPending(m_display))
328 {
329 XNextEvent(m_display, &event);
330
331 if (event.xcookie.type != GenericEvent)
332 continue;
333 if (event.xcookie.extension != xi_opcode)
334 continue;
335 if (!XGetEventData(m_display, &event.xcookie))
336 continue;
337
338 switch (event.xcookie.evtype)
339 {
340 case XI_RawButtonPress:
341 case XI_RawButtonRelease:
342 update_mouse = true;
343 break;
344 case XI_RawKeyPress:
345 case XI_RawKeyRelease:
346 update_keyboard = true;
347 break;
348 case XI_RawMotion:
349 {
350 update_mouse = true;
351
352 XIRawEvent* raw_event = (XIRawEvent*)event.xcookie.data;
353 float values[4] = {};
354 size_t value_idx = 0;
355
356 // We only care about the first 4 axes, which should always be available at minimum
357 for (int i = 0; i < 4; ++i)
358 {
359 if (XIMaskIsSet(raw_event->valuators.mask, i))
360 {
361 values[i] = raw_event->raw_values[value_idx++];
362 }
363 }
364
365 delta_delta = values[0];
366 // test for inf and nan
367 if (delta_delta == delta_delta && 1 + delta_delta != delta_delta)
368 delta_x += delta_delta;
369
370 delta_delta = values[1];
371 // test for inf and nan
372 if (delta_delta == delta_delta && 1 + delta_delta != delta_delta)
373 delta_y += delta_delta;
374
375 // Scroll wheel input gets scaled to be similar to the mouse axes
376 delta_delta = values[3] * 8.0 / scroll_increment;
377 // test for inf and nan
378 if (delta_delta == delta_delta && 1 + delta_delta != delta_delta)
379 delta_z += delta_delta;
380
381 break;
382 }
383 }
384
385 XFreeEventData(m_display, &event.xcookie);
386 }
387
388 m_state.relative_mouse.x = delta_x;
389 m_state.relative_mouse.y = delta_y;
390 m_state.relative_mouse.z = delta_z;
391
392 // apply axis smoothing
393 m_state.axis.x *= MOUSE_AXIS_SMOOTHING;
394 m_state.axis.x += delta_x;
395 m_state.axis.x /= MOUSE_AXIS_SMOOTHING + 1.0f;
396 m_state.axis.y *= MOUSE_AXIS_SMOOTHING;
397 m_state.axis.y += delta_y;
398 m_state.axis.y /= MOUSE_AXIS_SMOOTHING + 1.0f;
399 m_state.axis.z += delta_z;
400 m_state.axis.z /= SCROLL_AXIS_DECAY;
401
402 const bool should_center_mouse = g_controller_interface.IsMouseCenteringRequested() &&
403 (Host_RendererHasFocus() || Host_TASInputHasFocus());
404
405 // When a TAS Input window has focus and "Enable Controller Input" is checked most types of
406 // input should be read normally as if the render window had focus instead. The cursor is an
407 // exception, as otherwise using the mouse to set any control in the TAS Input window will also
408 // update the Wii IR value (or any other input controlled by the cursor).
409 const bool should_update_mouse = update_mouse && !Host_TASInputHasFocus();
410
411 if (should_update_mouse || should_center_mouse)
412 UpdateCursor(should_center_mouse);
413
414 if (update_keyboard)
415 XQueryKeymap(m_display, m_state.keyboard.data());
416
417 return Core::DeviceRemoval::Keep;
418 }
419
420 std::string KeyboardMouse::GetName() const
421 {
422 // This is the name string we got from the X server for this master
423 // pointer/keyboard pair.
424 return name;
425 }
426
427 std::string KeyboardMouse::GetSource() const
428 {
429 return std::string(SOURCE_NAME);
430 }
431
432 int KeyboardMouse::GetSortPriority() const
433 {
434 return DEFAULT_DEVICE_SORT_PRIORITY;
435 }
436
437 KeyboardMouse::Key::Key(std::string key_name, KeyCode keycode, const char* keyboard)
438 : m_keyname{std::move(key_name)}, m_keyboard(keyboard), m_keycodes{keycode}
439 {
440 }
441
442 const char* KeyboardMouse::Key::GetNameForKeyCode(Display* const display, KeyCode keycode)
443 {
444 int i = 0;
445 KeySym keysym = 0;
446 do
447 {
448 keysym = XkbKeycodeToKeysym(display, keycode, i, 0);
449 i++;
450 } while (keysym == NoSymbol && i < 8);
451
452 // Convert to upper case for the keyname
453 if (keysym >= 97 && keysym <= 122)
454 keysym -= 32;
455
456 // 0x0110ffff is the top of the unicode character range according
457 // to keysymdef.h although it is probably more than we need.
458 if (keysym == NoSymbol || keysym > 0x0110ffff || XKeysymToString(keysym) == nullptr)
459 return nullptr;
460
461 return XKeysymToString(keysym);
462 }
463
464 ControlState KeyboardMouse::Key::GetState() const
465 {
466 return ControlState(
467 std::ranges::any_of(m_keycodes, std::bind_front(&Key::IsKeyCodePressed, this)));
468 }
469
470 void KeyboardMouse::Key::AddKeyCode(KeyCode keycode)
471 {
472 m_keycodes.emplace_back(keycode);
473 }
474
475 bool KeyboardMouse::Key::IsKeyCodePressed(KeyCode keycode) const
476 {
477 return (m_keyboard[keycode / 8] & (1 << (keycode % 8))) != 0;
478 }
479
480 KeyboardMouse::Button::Button(unsigned int index, u32* buttons) : m_buttons(buttons), m_index(index)
481 {
482 name = fmt::format("Click {}", m_index + 1);
483 }
484
485 ControlState KeyboardMouse::Button::GetState() const
486 {
487 return ((*m_buttons & (1 << m_index)) != 0);
488 }
489
490 KeyboardMouse::Cursor::Cursor(u8 index, bool positive, const float* cursor)
491 : m_cursor(cursor), m_index(index), m_positive(positive)
492 {
493 name = fmt::format("Cursor {}{}", static_cast<char>('X' + m_index), (m_positive ? '+' : '-'));
494 }
495
496 ControlState KeyboardMouse::Cursor::GetState() const
497 {
498 return std::max(0.0f, *m_cursor / (m_positive ? 1.0f : -1.0f));
499 }
500
501 KeyboardMouse::Axis::Axis(u8 index, bool positive, const float* axis)
502 : m_axis(axis), m_index(index), m_positive(positive)
503 {
504 name = fmt::format("Axis {}{}", static_cast<char>('X' + m_index), (m_positive ? '+' : '-'));
505 }
506
507 KeyboardMouse::RelativeMouse::RelativeMouse(u8 index, bool positive, const float* axis)
508 : m_axis(axis), m_index(index), m_positive(positive)
509 {
510 name =
511 fmt::format("RelativeMouse {}{}", static_cast<char>('X' + m_index), (m_positive ? '+' : '-'));
512 }
513
514 ControlState KeyboardMouse::Axis::GetState() const
515 {
516 return std::max(0.0f, *m_axis / (m_positive ? MOUSE_AXIS_SENSITIVITY : -MOUSE_AXIS_SENSITIVITY));
517 }
518
519 ControlState KeyboardMouse::RelativeMouse::GetState() const
520 {
521 return std::max(0.0f, *m_axis / (m_positive ? MOUSE_AXIS_SENSITIVITY : -MOUSE_AXIS_SENSITIVITY));
522 }
523 } // namespace ciface::XInput2