Debian Codegraph @

Source/Core/InputCommon/ControllerInterface/Android/Android.cpp

raw symbols SCIP
1 // Copyright 2021 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerInterface/Android/Android.h"
5
6 #include <algorithm>
7 #include <atomic>
8 #include <chrono>
9 #include <memory>
10 #include <string>
11 #include <unordered_map>
12 #include <utility>
13
14 #include <fmt/format.h>
15
16 #include <android/input.h>
17 #include <android/keycodes.h>
18 #include <jni.h>
19
20 #include "Common/Assert.h"
21 #include "Common/Contains.h"
22 #include "Common/Logging/Log.h"
23 #include "Common/StringUtil.h"
24
25 #include "InputCommon/ControllerInterface/ControllerInterface.h"
26
27 #include "InputCommon/ControllerInterface/InputBackend.h"
28 #include "jni/AndroidCommon/AndroidCommon.h"
29 #include "jni/AndroidCommon/IDCache.h"
30 #include "jni/Input/CoreDevice.h"
31
32 namespace
33 {
34 std::string SOURCE = "Android";
35
36 jclass s_list_class;
37 jmethodID s_list_get;
38 jmethodID s_list_size;
39
40 jclass s_input_device_class;
41 jmethodID s_input_device_get_device_ids;
42 jmethodID s_input_device_get_device;
43 jmethodID s_input_device_get_controller_number;
44 jmethodID s_input_device_get_motion_ranges;
45 jmethodID s_input_device_get_name;
46 jmethodID s_input_device_get_sources;
47 jmethodID s_input_device_has_keys;
48
49 jclass s_motion_range_class;
50 jmethodID s_motion_range_get_axis;
51 jmethodID s_motion_range_get_max;
52 jmethodID s_motion_range_get_min;
53 jmethodID s_motion_range_get_source;
54
55 jclass s_input_event_class;
56 jmethodID s_input_event_get_device_id;
57
58 jclass s_key_event_class;
59 jmethodID s_key_event_get_action;
60 jmethodID s_key_event_get_keycode;
61
62 jclass s_motion_event_class;
63 jmethodID s_motion_event_get_axis_value;
64 jmethodID s_motion_event_get_source;
65
66 jclass s_controller_interface_class;
67 jmethodID s_controller_interface_register_input_device_listener;
68 jmethodID s_controller_interface_unregister_input_device_listener;
69 jmethodID s_controller_interface_get_vibrator_manager;
70 jmethodID s_controller_interface_get_system_vibrator_manager;
71 jmethodID s_controller_interface_vibrate;
72
73 jclass s_sensor_event_listener_class;
74 jmethodID s_sensor_event_listener_constructor;
75 jmethodID s_sensor_event_listener_constructor_input_device;
76 jmethodID s_sensor_event_listener_set_device_qualifier;
77 jmethodID s_sensor_event_listener_request_unsuspend_sensor;
78 jmethodID s_sensor_event_listener_get_axis_names;
79 jmethodID s_sensor_event_listener_get_negative_axes;
80
81 jclass s_dolphin_vibrator_manager_class;
82 jmethodID s_dolphin_vibrator_manager_get_vibrator;
83 jmethodID s_dolphin_vibrator_manager_get_vibrator_ids;
84
85 jintArray s_keycodes_array;
86
87 using Clock = std::chrono::steady_clock;
88 constexpr Clock::duration ACTIVE_INPUT_TIMEOUT = std::chrono::milliseconds(1000);
89
90 std::unordered_map<jint, ciface::Core::DeviceQualifier> s_device_id_to_device_qualifier;
91
92 constexpr int MAX_KEYCODE = AKEYCODE_PROFILE_SWITCH; // Up to date as of SDK 31
93
94 const std::array<std::string_view, MAX_KEYCODE + 1> KEYCODE_NAMES = {
95 "Unknown",
96 "Soft Left",
97 "Soft Right",
98 "Home",
99 "Back",
100 "Call",
101 "End Call",
102 "0",
103 "1",
104 "2",
105 "3",
106 "4",
107 "5",
108 "6",
109 "7",
110 "8",
111 "9",
112 "Star",
113 "Pound",
114 "Up",
115 "Down",
116 "Left",
117 "Right",
118 "Center",
119 "Volume Up",
120 "Volume Down",
121 "Power",
122 "Camera",
123 "Clear",
124 "A",
125 "B",
126 "C",
127 "D",
128 "E",
129 "F",
130 "G",
131 "H",
132 "I",
133 "J",
134 "K",
135 "L",
136 "M",
137 "N",
138 "O",
139 "P",
140 "Q",
141 "R",
142 "S",
143 "T",
144 "U",
145 "V",
146 "W",
147 "X",
148 "Y",
149 "Z",
150 "Comma",
151 "Period",
152 "Left Alt",
153 "Right Alt",
154 "Left Shift",
155 "Right Shift",
156 "Tab",
157 "Space",
158 "Sym",
159 "Explorer",
160 "Envelope",
161 "Enter",
162 "Backspace",
163 "Grave",
164 "Minus",
165 "Equals",
166 "Left Bracket",
167 "Right Bracket",
168 "Backslash",
169 "Semicolon",
170 "Apostrophe",
171 "Slash",
172 "At",
173 "Num",
174 "Headset Hook",
175 "Focus",
176 "Plus",
177 "Menu",
178 "Notification",
179 "Search",
180 "Play Pause",
181 "Stop",
182 "Next",
183 "Previous",
184 "Rewind",
185 "Fast Forward",
186 "Mute",
187 "Page Up",
188 "Page Down",
189 "Emoji",
190 "Switch Charset",
191 "Button A",
192 "Button B",
193 "Button C",
194 "Button X",
195 "Button Y",
196 "Button Z",
197 "Button L1",
198 "Button R1",
199 "Button L2",
200 "Button R2",
201 "Button L3",
202 "Button R3",
203 "Start",
204 "Select",
205 "Mode",
206 "Escape",
207 "Delete",
208 "Left Ctrl",
209 "Right Ctrl",
210 "Caps Lock",
211 "Scroll Lock",
212 "Left Meta",
213 "Right Meta",
214 "Fn",
215 "PrtSc SysRq",
216 "Pause Break",
217 "Move Home",
218 "Move End",
219 "Insert",
220 "Forward",
221 "Play",
222 "Pause",
223 "Close",
224 "Eject",
225 "Record",
226 "F1",
227 "F2",
228 "F3",
229 "F4",
230 "F5",
231 "F6",
232 "F7",
233 "F8",
234 "F9",
235 "F10",
236 "F11",
237 "F12",
238 "Num Lock",
239 "Numpad 0",
240 "Numpad 1",
241 "Numpad 2",
242 "Numpad 3",
243 "Numpad 4",
244 "Numpad 5",
245 "Numpad 6",
246 "Numpad 7",
247 "Numpad 8",
248 "Numpad 9",
249 "Numpad Divide",
250 "Numpad Multiply",
251 "Numpad Subtract",
252 "Numpad Add",
253 "Numpad Dot",
254 "Numpad Comma",
255 "Numpad Enter",
256 "Numpad Equals",
257 "Numpad Left Paren",
258 "Numpad Right Paren",
259 "Volume Mute",
260 "Info",
261 "Channel Up",
262 "Channel Down",
263 "Zoom In",
264 "Zoom Out",
265 "TV",
266 "Window",
267 "Guide",
268 "DVR",
269 "Bookmark",
270 "Captions",
271 "Settings",
272 "TV Power",
273 "TV Input",
274 "STB Power",
275 "STB Input",
276 "AVR Power",
277 "AVR Input",
278 "Prog Red",
279 "Prog Green",
280 "Prog Yellow",
281 "Prog Blue",
282 "App Switch",
283 "Button 1",
284 "Button 2",
285 "Button 3",
286 "Button 4",
287 "Button 5",
288 "Button 6",
289 "Button 7",
290 "Button 8",
291 "Button 9",
292 "Button 10",
293 "Button 11",
294 "Button 12",
295 "Button 13",
296 "Button 14",
297 "Button 15",
298 "Button 16",
299 "Language Switch",
300 "Manner Mode",
301 "3D Mode",
302 "Contacts",
303 "Calendar",
304 "Music",
305 "Calculator",
306 "Zenkaku Hankaku",
307 "Eisu",
308 "Henkan",
309 "Muhenkan",
310 "Katakana Hiragana",
311 "Yen",
312 "Ro",
313 "Kana",
314 "Assist",
315 "Brightness Down",
316 "Brightness Up",
317 "Audio Track",
318 "Sleep",
319 "Wakeup",
320 "Pairing",
321 "Top Menu",
322 "11",
323 "12",
324 "Last Channel",
325 "Data Service",
326 "Voice Assist",
327 "Radio Service",
328 "Teletext",
329 "Number Entry",
330 "Terrestrial Analog",
331 "Terrestrial Digital",
332 "Satellite",
333 "Satellite BS",
334 "Satellite CS",
335 "Satellite Service",
336 "Network",
337 "Antenna Cable",
338 "Input HDMI 1",
339 "Input HDMI 2",
340 "Input HDMI 3",
341 "Input HDMI 4",
342 "Input Composite 1",
343 "Input Composite 2",
344 "Input Component 1",
345 "Input Component 2",
346 "Input VGA 1",
347 "Audio Description",
348 "Audio Description Mix Up",
349 "Audio Description Mix Down",
350 "Zoom Mode",
351 "Contents Menu",
352 "Media Context Menu",
353 "Timer Programming",
354 "Help",
355 "Navigate Previous",
356 "Navigate Next",
357 "Navigate In",
358 "Navigate Out",
359 "Stem Primary",
360 "Stem 1",
361 "Stem 2",
362 "Stem 3",
363 "Up Left",
364 "Down Left",
365 "Up Right",
366 "Down Right",
367 "Skip Forward",
368 "Skip Backward",
369 "Step Forward",
370 "Step Backward",
371 "Soft Sleep",
372 "Cut",
373 "Copy",
374 "Paste",
375 "System Navigation Up",
376 "System Navigation Down",
377 "System Navigation Left",
378 "System Navigation Right",
379 "All Apps",
380 "Refresh",
381 "Thumbs Up",
382 "Thumbs Down",
383 "Profile Switch",
384 };
385
386 std::string ConstructKeyName(int keycode)
387 {
388 return std::string(KEYCODE_NAMES[keycode]);
389 }
390
391 std::string ConstructAxisNamePrefix(int source)
392 {
393 // A device is allowed to have two axes with the same axis ID but different source IDs,
394 // so we have to make sure to include the source in the axis name.
395
396 static const std::unordered_map<int, std::string> source_names{
397 {AINPUT_SOURCE_KEYBOARD, "Keyboard"},
398 {AINPUT_SOURCE_DPAD, "Dpad"},
399 {AINPUT_SOURCE_GAMEPAD, "Gamepad"},
400 {AINPUT_SOURCE_TOUCHSCREEN, "Touch"},
401 {AINPUT_SOURCE_MOUSE, "Cursor"},
402 {AINPUT_SOURCE_STYLUS, "Stylus"},
403 {AINPUT_SOURCE_BLUETOOTH_STYLUS, "BTStylus"},
404 {AINPUT_SOURCE_TRACKBALL, "Trackball"},
405 {AINPUT_SOURCE_MOUSE_RELATIVE, "Mouse"},
406 {AINPUT_SOURCE_TOUCHPAD, "Touchpad"},
407 {AINPUT_SOURCE_TOUCH_NAVIGATION, "Touchnav"},
408 {AINPUT_SOURCE_JOYSTICK, "Axis"}, // The typical source for all axes on a gamepad
409 {AINPUT_SOURCE_HDMI, "HDMI"},
410 {AINPUT_SOURCE_SENSOR, "Sensor"},
411 {AINPUT_SOURCE_ROTARY_ENCODER, "Rotary"},
412 };
413
414 const auto it = source_names.find(source);
415 if (it != source_names.end())
416 return fmt::format("{} ", it->second);
417 else
418 return fmt::format("Axis {:08x}/", source);
419 }
420
421 std::string ConstructAxisName(int source, int axis, bool negative)
422 {
423 const char sign = negative ? '-' : '+';
424 return fmt::format("{}{}{}", ConstructAxisNamePrefix(source), axis, sign);
425 }
426
427 std::shared_ptr<ciface::Core::Device> FindDevice(jint device_id)
428 {
429 const auto it = s_device_id_to_device_qualifier.find(device_id);
430 if (it == s_device_id_to_device_qualifier.end())
431 {
432 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Could not find device ID {}", device_id);
433 return nullptr;
434 }
435
436 const ciface::Core::DeviceQualifier& qualifier = it->second;
437 std::shared_ptr<ciface::Core::Device> device = g_controller_interface.FindDevice(qualifier);
438 if (!device)
439 {
440 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Could not find device {}", qualifier.ToString());
441 return nullptr;
442 }
443
444 return device;
445 }
446
447 void RegisterDevicesChangedCallbackIfNeeded(JNIEnv* env, jclass controller_interface_class)
448 {
449 static bool registered = false;
450 if (registered)
451 return;
452 registered = true;
453
454 const jclass global_controller_interface_class =
455 reinterpret_cast<jclass>(env->NewGlobalRef(controller_interface_class));
456 const jmethodID controller_interface_on_devices_changed =
457 env->GetStaticMethodID(global_controller_interface_class, "onDevicesChanged", "()V");
458
459 static Common::EventHook event_hook = g_controller_interface.RegisterDevicesChangedCallback(
460 [global_controller_interface_class, controller_interface_on_devices_changed] {
461 IDCache::GetEnvForThread()->CallStaticVoidMethod(global_controller_interface_class,
462 controller_interface_on_devices_changed);
463 });
464 }
465
466 } // namespace
467
468 namespace ciface::Android
469 {
470 class InputBackend final : public ciface::InputBackend
471 {
472 public:
473 explicit InputBackend(ControllerInterface* controller_interface);
474 ~InputBackend();
475 void PopulateDevices() override;
476
477 static void AddDevice(JNIEnv* env, int device_id);
478 static void AddSensorDevice(JNIEnv* env);
479 static void RemoveDevice(int device_id);
480 };
481
482 std::unique_ptr<ciface::InputBackend> CreateInputBackend(ControllerInterface* controller_interface)
483 {
484 return std::make_unique<InputBackend>(controller_interface);
485 }
486
487 class AndroidInput : public Core::Device::Input
488 {
489 public:
490 explicit AndroidInput(std::string name) : m_name(std::move(name))
491 {
492 DEBUG_LOG_FMT(CONTROLLERINTERFACE, "Created {}", m_name);
493 }
494
495 std::string GetName() const override { return m_name; }
496
497 ControlState GetState() const override
498 {
499 m_last_polled.store(Clock::now(), std::memory_order_relaxed);
500 return m_state.load(std::memory_order_relaxed);
501 }
502
503 void SetState(ControlState state) { m_state.store(state, std::memory_order_relaxed); }
504
505 Clock::time_point GetLastPolled() const { return m_last_polled.load(std::memory_order_relaxed); }
506
507 private:
508 std::string m_name;
509 std::atomic<ControlState> m_state = 0;
510 mutable std::atomic<Clock::time_point> m_last_polled{};
511 };
512
513 class AndroidKey final : public AndroidInput
514 {
515 public:
516 explicit AndroidKey(int keycode) : AndroidInput(ConstructKeyName(keycode)) {}
517 };
518
519 class AndroidAxis : public AndroidInput
520 {
521 public:
522 AndroidAxis(int source, int axis, bool negative)
523 : AndroidInput(ConstructAxisName(source, axis, negative)), m_negative(negative)
524 {
525 }
526
527 AndroidAxis(std::string name, bool negative) : AndroidInput(std::move(name)), m_negative(negative)
528 {
529 }
530
531 ControlState GetState() const override
532 {
533 return m_negative ? -AndroidInput::GetState() : AndroidInput::GetState();
534 }
535
536 private:
537 bool m_negative;
538 };
539
540 class AndroidSensorAxis final : public AndroidAxis
541 {
542 public:
543 // This class does not create its own global reference to the passed-in sensor_event_listener.
544 // That is, it's up to the device that contains this axis to keep sensor_event_listener valid.
545 // It does however create its own global reference to the passed-in name.
546 AndroidSensorAxis(JNIEnv* env, jobject sensor_event_listener, jstring j_name, bool negative)
547 : AndroidAxis(GetJString(env, j_name), negative),
548 m_sensor_event_listener(sensor_event_listener),
549 m_j_name(reinterpret_cast<jstring>(env->NewGlobalRef(j_name)))
550 {
551 }
552
553 ~AndroidSensorAxis() { IDCache::GetEnvForThread()->DeleteGlobalRef(m_j_name); }
554
555 bool IsDetectable() const override { return false; }
556
557 ControlState GetState() const override
558 {
559 if (m_is_suspended.load(std::memory_order_relaxed))
560 {
561 IDCache::GetEnvForThread()->CallVoidMethod(
562 m_sensor_event_listener, s_sensor_event_listener_request_unsuspend_sensor, m_j_name);
563
564 // m_is_suspended is intentionally not updated here. To prevent the C++ suspended status from
565 // ending up desynced with the Java suspended status, we only update m_is_suspended when Java
566 // calls notifySensorSuspendedState (which calls NotifyIsSuspended). This way, Java is the
567 // authoritative source for the suspended status, and C++ mirrors it (possibly with a delay).
568 }
569
570 return AndroidAxis::GetState();
571 }
572
573 void NotifyIsSuspended(bool is_suspended)
574 {
575 m_is_suspended.store(is_suspended, std::memory_order_relaxed);
576 }
577
578 private:
579 const jobject m_sensor_event_listener;
580 const jstring m_j_name;
581 std::atomic<bool> m_is_suspended = true;
582 };
583
584 class AndroidMotor : public Core::Device::Output
585 {
586 public:
587 AndroidMotor(JNIEnv* env, jobject vibrator, jint id)
588 : m_vibrator(env->NewGlobalRef(vibrator)), m_id(id)
589 {
590 }
591
592 ~AndroidMotor() { IDCache::GetEnvForThread()->DeleteGlobalRef(m_vibrator); }
593
594 std::string GetName() const override { return "Motor " + std::to_string(m_id); }
595
596 void SetState(ControlState state) override
597 {
598 ControlState old_state = m_state.exchange(state, std::memory_order_relaxed);
599
600 if (old_state < 0.5 && state >= 0.5)
601 {
602 IDCache::GetEnvForThread()->CallStaticVoidMethod(s_controller_interface_class,
603 s_controller_interface_vibrate, m_vibrator);
604 }
605 }
606
607 private:
608 const jobject m_vibrator;
609 const jint m_id;
610 std::atomic<ControlState> m_state = 0;
611 };
612
613 class AndroidDevice final : public Core::Device
614 {
615 public:
616 AndroidDevice(JNIEnv* env, jint device_id, jobject input_device)
617 : m_sensor_event_listener(AddSensors(env, input_device)),
618 m_source(env->CallIntMethod(input_device, s_input_device_get_sources)),
619 m_controller_number(env->CallIntMethod(input_device, s_input_device_get_controller_number)),
620 m_device_id(device_id)
621 {
622 jstring j_name =
623 reinterpret_cast<jstring>(env->CallObjectMethod(input_device, s_input_device_get_name));
624 m_name = GetJString(env, j_name);
625 env->DeleteLocalRef(j_name);
626
627 DEBUG_LOG_FMT(CONTROLLERINTERFACE, "Sources for {}: {:08x}", GetQualifiedName(), m_source);
628
629 AddKeys(env, input_device);
630 AddAxes(env, input_device);
631 AddMotors(env, input_device);
632 }
633
634 // Constructor for the device added by Dolphin to contain sensor inputs
635 AndroidDevice(JNIEnv* env, std::string name)
636 : m_sensor_event_listener(AddSensors(env, nullptr)), m_source(AINPUT_SOURCE_SENSOR),
637 m_controller_number(0), m_device_id(std::nullopt), m_name(std::move(name))
638 {
639 AddSystemMotors(env);
640 }
641
642 ~AndroidDevice()
643 {
644 if (m_sensor_event_listener)
645 IDCache::GetEnvForThread()->DeleteGlobalRef(m_sensor_event_listener);
646 }
647
648 std::string GetName() const override { return m_name; }
649
650 std::string GetSource() const override { return SOURCE; }
651
652 std::optional<int> GetPreferredId() const override
653 {
654 return m_controller_number != 0 ? std::make_optional(m_controller_number) : std::nullopt;
655 }
656
657 int GetSortPriority() const override
658 {
659 // If m_controller_number is non-zero, Android considers this to be a gamepad
660 if (m_controller_number != 0)
661 return 0;
662
663 if ((m_source & AINPUT_SOURCE_KEYBOARD) != 0)
664 return -1;
665
666 if ((m_source & (AINPUT_SOURCE_MOUSE | AINPUT_SOURCE_MOUSE_RELATIVE)) != 0)
667 return -2;
668
669 return -3;
670 }
671
672 std::optional<jint> GetDeviceID() const { return m_device_id; }
673
674 jobject GetSensorEventListener() { return m_sensor_event_listener; }
675
676 private:
677 void AddKeys(JNIEnv* env, jobject input_device)
678 {
679 jbooleanArray keys_array = reinterpret_cast<jbooleanArray>(
680 env->CallObjectMethod(input_device, s_input_device_has_keys, s_keycodes_array));
681 jboolean* keys = env->GetBooleanArrayElements(keys_array, nullptr);
682 jsize keys_count = env->GetArrayLength(keys_array);
683 for (jsize i = 0; i < keys_count; ++i)
684 {
685 // These specific keys never get delivered to applications,
686 // so there's no point in letting users try to map them
687 if (i == AKEYCODE_HOME || i == AKEYCODE_ASSIST || i == AKEYCODE_VOICE_ASSIST)
688 continue;
689
690 if (keys[i])
691 AddInput(new AndroidKey(i));
692 }
693 env->ReleaseBooleanArrayElements(keys_array, keys, JNI_ABORT);
694 env->DeleteLocalRef(keys_array);
695 }
696
697 void AddAxes(JNIEnv* env, jobject input_device)
698 {
699 jobject motion_ranges_list =
700 env->CallObjectMethod(input_device, s_input_device_get_motion_ranges);
701 jint motion_ranges_count = env->CallIntMethod(motion_ranges_list, s_list_size);
702 for (jint i = 0; i < motion_ranges_count; ++i)
703 {
704 jobject motion_range = env->CallObjectMethod(motion_ranges_list, s_list_get, i);
705
706 jint source = env->CallIntMethod(motion_range, s_motion_range_get_source);
707 jint axis = env->CallIntMethod(motion_range, s_motion_range_get_axis);
708 jfloat min = env->CallFloatMethod(motion_range, s_motion_range_get_min);
709 jfloat max = env->CallFloatMethod(motion_range, s_motion_range_get_max);
710
711 env->DeleteLocalRef(motion_range);
712
713 AndroidAxis* positive = nullptr;
714 AndroidAxis* negative = nullptr;
715 if (max > 0)
716 positive = new AndroidAxis(source, axis, false);
717 if (min < 0)
718 negative = new AndroidAxis(source, axis, true);
719
720 if (positive && negative)
721 AddFullAnalogSurfaceInputs(positive, negative);
722 else if (positive || negative)
723 AddInput(positive ? positive : negative);
724 }
725 env->DeleteLocalRef(motion_ranges_list);
726 }
727
728 jobject AddSensors(JNIEnv* env, jobject input_device)
729 {
730 jobject local_sensor_event_listener;
731 if (input_device)
732 {
733 local_sensor_event_listener =
734 env->NewObject(s_sensor_event_listener_class,
735 s_sensor_event_listener_constructor_input_device, input_device);
736 }
737 else
738 {
739 local_sensor_event_listener =
740 env->NewObject(s_sensor_event_listener_class, s_sensor_event_listener_constructor);
741 }
742
743 jobject sensor_event_listener = env->NewGlobalRef(local_sensor_event_listener);
744
745 env->DeleteLocalRef(local_sensor_event_listener);
746
747 jobjectArray j_axis_names = reinterpret_cast<jobjectArray>(
748 env->CallObjectMethod(sensor_event_listener, s_sensor_event_listener_get_axis_names));
749
750 jbooleanArray j_negative_axes = reinterpret_cast<jbooleanArray>(
751 env->CallObjectMethod(sensor_event_listener, s_sensor_event_listener_get_negative_axes));
752 jboolean* negative_axes = env->GetBooleanArrayElements(j_negative_axes, nullptr);
753
754 const jsize axis_count = env->GetArrayLength(j_axis_names);
755 ASSERT(axis_count == env->GetArrayLength(j_negative_axes));
756 for (jsize i = 0; i < axis_count; ++i)
757 {
758 const jstring axis_name =
759 reinterpret_cast<jstring>(env->GetObjectArrayElement(j_axis_names, i));
760 AddInput(new AndroidSensorAxis(env, sensor_event_listener, axis_name, negative_axes[i]));
761 env->DeleteLocalRef(axis_name);
762 }
763
764 env->DeleteLocalRef(j_axis_names);
765 env->ReleaseBooleanArrayElements(j_negative_axes, negative_axes, 0);
766 env->DeleteLocalRef(j_negative_axes);
767
768 return sensor_event_listener;
769 }
770
771 void AddMotors(JNIEnv* env, jobject input_device)
772 {
773 jobject vibrator_manager = env->CallStaticObjectMethod(
774 s_controller_interface_class, s_controller_interface_get_vibrator_manager, input_device);
775 AddMotorsFromManager(env, vibrator_manager);
776 env->DeleteLocalRef(vibrator_manager);
777 }
778
779 void AddSystemMotors(JNIEnv* env)
780 {
781 jobject vibrator_manager = env->CallStaticObjectMethod(
782 s_controller_interface_class, s_controller_interface_get_system_vibrator_manager);
783 AddMotorsFromManager(env, vibrator_manager);
784 env->DeleteLocalRef(vibrator_manager);
785 }
786
787 void AddMotorsFromManager(JNIEnv* env, jobject vibrator_manager)
788 {
789 jintArray j_vibrator_ids = reinterpret_cast<jintArray>(
790 env->CallObjectMethod(vibrator_manager, s_dolphin_vibrator_manager_get_vibrator_ids));
791 jint* vibrator_ids = env->GetIntArrayElements(j_vibrator_ids, nullptr);
792
793 jint size = env->GetArrayLength(j_vibrator_ids);
794 for (jint i = 0; i < size; ++i)
795 {
796 jobject vibrator =
797 env->CallObjectMethod(vibrator_manager, s_dolphin_vibrator_manager_get_vibrator, i);
798 AddOutput(new AndroidMotor(env, vibrator, i));
799 env->DeleteLocalRef(vibrator);
800 }
801
802 env->ReleaseIntArrayElements(j_vibrator_ids, vibrator_ids, 0);
803 env->DeleteLocalRef(j_vibrator_ids);
804 }
805
806 const jobject m_sensor_event_listener;
807 const int m_source;
808 const int m_controller_number;
809 const std::optional<jint> m_device_id;
810 std::string m_name;
811 };
812
813 // Creates an array that contains every possible keycode
814 static jintArray CreateKeyCodesArray(JNIEnv* env)
815 {
816 jintArray keycodes_array = env->NewIntArray(MAX_KEYCODE + 1);
817
818 int* keycodes = env->GetIntArrayElements(keycodes_array, nullptr);
819 for (int i = 0; i <= MAX_KEYCODE; ++i)
820 keycodes[i] = i;
821 env->ReleaseIntArrayElements(keycodes_array, keycodes, 0);
822
823 return keycodes_array;
824 }
825
826 InputBackend::InputBackend(ControllerInterface* controller_interface)
827 : ciface::InputBackend(controller_interface)
828 {
829 JNIEnv* env = IDCache::GetEnvForThread();
830
831 const jclass list_class = env->FindClass("java/util/List");
832 s_list_class = reinterpret_cast<jclass>(env->NewGlobalRef(list_class));
833 s_list_get = env->GetMethodID(s_list_class, "get", "(I)Ljava/lang/Object;");
834 s_list_size = env->GetMethodID(s_list_class, "size", "()I");
835 env->DeleteLocalRef(list_class);
836
837 const jclass input_device_class = env->FindClass("android/view/InputDevice");
838 s_input_device_class = reinterpret_cast<jclass>(env->NewGlobalRef(input_device_class));
839 s_input_device_get_device_ids =
840 env->GetStaticMethodID(s_input_device_class, "getDeviceIds", "()[I");
841 s_input_device_get_device =
842 env->GetStaticMethodID(s_input_device_class, "getDevice", "(I)Landroid/view/InputDevice;");
843 s_input_device_get_controller_number =
844 env->GetMethodID(s_input_device_class, "getControllerNumber", "()I");
845 s_input_device_get_motion_ranges =
846 env->GetMethodID(s_input_device_class, "getMotionRanges", "()Ljava/util/List;");
847 s_input_device_get_name =
848 env->GetMethodID(s_input_device_class, "getName", "()Ljava/lang/String;");
849 s_input_device_get_sources = env->GetMethodID(s_input_device_class, "getSources", "()I");
850 s_input_device_has_keys = env->GetMethodID(s_input_device_class, "hasKeys", "([I)[Z");
851 env->DeleteLocalRef(input_device_class);
852
853 const jclass motion_range_class = env->FindClass("android/view/InputDevice$MotionRange");
854 s_motion_range_class = reinterpret_cast<jclass>(env->NewGlobalRef(motion_range_class));
855 s_motion_range_get_axis = env->GetMethodID(s_motion_range_class, "getAxis", "()I");
856 s_motion_range_get_max = env->GetMethodID(s_motion_range_class, "getMax", "()F");
857 s_motion_range_get_min = env->GetMethodID(s_motion_range_class, "getMin", "()F");
858 s_motion_range_get_source = env->GetMethodID(s_motion_range_class, "getSource", "()I");
859 env->DeleteLocalRef(motion_range_class);
860
861 const jclass input_event_class = env->FindClass("android/view/InputEvent");
862 s_input_event_class = reinterpret_cast<jclass>(env->NewGlobalRef(input_event_class));
863 s_input_event_get_device_id = env->GetMethodID(s_input_event_class, "getDeviceId", "()I");
864 env->DeleteLocalRef(input_event_class);
865
866 const jclass key_event_class = env->FindClass("android/view/KeyEvent");
867 s_key_event_class = reinterpret_cast<jclass>(env->NewGlobalRef(key_event_class));
868 s_key_event_get_action = env->GetMethodID(s_key_event_class, "getAction", "()I");
869 s_key_event_get_keycode = env->GetMethodID(s_key_event_class, "getKeyCode", "()I");
870 env->DeleteLocalRef(key_event_class);
871
872 const jclass motion_event_class = env->FindClass("android/view/MotionEvent");
873 s_motion_event_class = reinterpret_cast<jclass>(env->NewGlobalRef(motion_event_class));
874 s_motion_event_get_axis_value = env->GetMethodID(s_motion_event_class, "getAxisValue", "(I)F");
875 s_motion_event_get_source = env->GetMethodID(s_motion_event_class, "getSource", "()I");
876 env->DeleteLocalRef(motion_event_class);
877
878 const jclass controller_interface_class =
879 env->FindClass("org/dolphinemu/dolphinemu/features/input/model/ControllerInterface");
880 s_controller_interface_class =
881 reinterpret_cast<jclass>(env->NewGlobalRef(controller_interface_class));
882 s_controller_interface_register_input_device_listener =
883 env->GetStaticMethodID(s_controller_interface_class, "registerInputDeviceListener", "()V");
884 s_controller_interface_unregister_input_device_listener =
885 env->GetStaticMethodID(s_controller_interface_class, "unregisterInputDeviceListener", "()V");
886 s_controller_interface_get_vibrator_manager =
887 env->GetStaticMethodID(s_controller_interface_class, "getVibratorManager",
888 "(Landroid/view/InputDevice;)Lorg/dolphinemu/dolphinemu/features/"
889 "input/model/DolphinVibratorManager;");
890 s_controller_interface_get_system_vibrator_manager = env->GetStaticMethodID(
891 s_controller_interface_class, "getSystemVibratorManager",
892 "()Lorg/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManager;");
893 s_controller_interface_vibrate =
894 env->GetStaticMethodID(s_controller_interface_class, "vibrate", "(Landroid/os/Vibrator;)V");
895 env->DeleteLocalRef(controller_interface_class);
896
897 const jclass sensor_event_listener_class =
898 env->FindClass("org/dolphinemu/dolphinemu/features/input/model/DolphinSensorEventListener");
899 s_sensor_event_listener_class =
900 reinterpret_cast<jclass>(env->NewGlobalRef(sensor_event_listener_class));
901 s_sensor_event_listener_constructor =
902 env->GetMethodID(s_sensor_event_listener_class, "<init>", "()V");
903 s_sensor_event_listener_constructor_input_device =
904 env->GetMethodID(s_sensor_event_listener_class, "<init>", "(Landroid/view/InputDevice;)V");
905 s_sensor_event_listener_set_device_qualifier = env->GetMethodID(
906 s_sensor_event_listener_class, "setDeviceQualifier", "(Ljava/lang/String;)V");
907 s_sensor_event_listener_request_unsuspend_sensor = env->GetMethodID(
908 s_sensor_event_listener_class, "requestUnsuspendSensor", "(Ljava/lang/String;)V");
909 s_sensor_event_listener_get_axis_names =
910 env->GetMethodID(s_sensor_event_listener_class, "getAxisNames", "()[Ljava/lang/String;");
911 s_sensor_event_listener_get_negative_axes =
912 env->GetMethodID(s_sensor_event_listener_class, "getNegativeAxes", "()[Z");
913 env->DeleteLocalRef(sensor_event_listener_class);
914
915 const jclass dolphin_vibrator_manager_class =
916 env->FindClass("org/dolphinemu/dolphinemu/features/input/model/DolphinVibratorManager");
917 s_dolphin_vibrator_manager_class =
918 reinterpret_cast<jclass>(env->NewGlobalRef(dolphin_vibrator_manager_class));
919 s_dolphin_vibrator_manager_get_vibrator =
920 env->GetMethodID(s_dolphin_vibrator_manager_class, "getVibrator", "(I)Landroid/os/Vibrator;");
921 s_dolphin_vibrator_manager_get_vibrator_ids =
922 env->GetMethodID(s_dolphin_vibrator_manager_class, "getVibratorIds", "()[I");
923 env->DeleteLocalRef(dolphin_vibrator_manager_class);
924
925 jintArray keycodes_array = CreateKeyCodesArray(env);
926 s_keycodes_array = reinterpret_cast<jintArray>(env->NewGlobalRef(keycodes_array));
927 env->DeleteLocalRef(keycodes_array);
928
929 env->CallStaticVoidMethod(s_controller_interface_class,
930 s_controller_interface_register_input_device_listener);
931
932 RegisterDevicesChangedCallbackIfNeeded(env, s_controller_interface_class);
933 }
934
935 InputBackend::~InputBackend()
936 {
937 JNIEnv* env = IDCache::GetEnvForThread();
938
939 env->CallStaticVoidMethod(s_controller_interface_class,
940 s_controller_interface_unregister_input_device_listener);
941
942 env->DeleteGlobalRef(s_input_device_class);
943 env->DeleteGlobalRef(s_motion_range_class);
944 env->DeleteGlobalRef(s_input_event_class);
945 env->DeleteGlobalRef(s_key_event_class);
946 env->DeleteGlobalRef(s_motion_event_class);
947 env->DeleteGlobalRef(s_controller_interface_class);
948 env->DeleteGlobalRef(s_sensor_event_listener_class);
949 env->DeleteGlobalRef(s_dolphin_vibrator_manager_class);
950 env->DeleteGlobalRef(s_keycodes_array);
951 }
952
953 void InputBackend::AddDevice(JNIEnv* env, jint device_id)
954 {
955 // Remove the device in case it already exists (maybe it's possible for a device to connect,
956 // be processed by PopulateDevices, and then be processed by onInputDeviceAdded)
957 RemoveDevice(device_id);
958
959 jobject input_device =
960 env->CallStaticObjectMethod(s_input_device_class, s_input_device_get_device, device_id);
961
962 if (!input_device)
963 {
964 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Could not find device with ID {}", device_id);
965 return;
966 }
967
968 auto device = std::make_shared<AndroidDevice>(env, device_id, input_device);
969
970 env->DeleteLocalRef(input_device);
971
972 if (device->Inputs().empty() && device->Outputs().empty())
973 return;
974
975 g_controller_interface.AddDevice(device);
976
977 Core::DeviceQualifier qualifier;
978 qualifier.FromDevice(device.get());
979
980 INFO_LOG_FMT(CONTROLLERINTERFACE, "Added device ID {} as {}", device_id,
981 device->GetQualifiedName());
982 s_device_id_to_device_qualifier.emplace(device_id, qualifier);
983
984 jstring j_qualifier = ToJString(env, qualifier.ToString());
985 env->CallVoidMethod(device->GetSensorEventListener(),
986 s_sensor_event_listener_set_device_qualifier, j_qualifier);
987 env->DeleteLocalRef(j_qualifier);
988 }
989
990 void InputBackend::AddSensorDevice(JNIEnv* env)
991 {
992 // Device sensors (accelerometer, etc.) aren't associated with any Android InputDevice.
993 // Create an otherwise empty Dolphin input device so that they have somewhere to live.
994
995 auto device = std::make_shared<AndroidDevice>(env, "Device Sensors");
996
997 if (device->Inputs().empty() && device->Outputs().empty())
998 return;
999
1000 g_controller_interface.AddDevice(device);
1001
1002 Core::DeviceQualifier qualifier;
1003 qualifier.FromDevice(device.get());
1004
1005 INFO_LOG_FMT(CONTROLLERINTERFACE, "Added sensor device as {}", device->GetQualifiedName());
1006
1007 jstring j_qualifier = ToJString(env, qualifier.ToString());
1008 env->CallVoidMethod(device->GetSensorEventListener(),
1009 s_sensor_event_listener_set_device_qualifier, j_qualifier);
1010 env->DeleteLocalRef(j_qualifier);
1011 }
1012
1013 void InputBackend::RemoveDevice(jint device_id)
1014 {
1015 g_controller_interface.RemoveDevice([device_id](const ciface::Core::Device* device) {
1016 return device->GetSource() == SOURCE &&
1017 static_cast<const AndroidDevice*>(device)->GetDeviceID() == device_id;
1018 });
1019
1020 s_device_id_to_device_qualifier.erase(device_id);
1021 }
1022
1023 void InputBackend::PopulateDevices()
1024 {
1025 INFO_LOG_FMT(CONTROLLERINTERFACE, "Android populating devices");
1026
1027 JNIEnv* env = IDCache::GetEnvForThread();
1028
1029 jintArray device_ids_array = reinterpret_cast<jintArray>(
1030 env->CallStaticObjectMethod(s_input_device_class, s_input_device_get_device_ids));
1031 int* device_ids = env->GetIntArrayElements(device_ids_array, nullptr);
1032 jsize device_ids_count = env->GetArrayLength(device_ids_array);
1033 for (jsize i = 0; i < device_ids_count; ++i)
1034 AddDevice(env, device_ids[i]);
1035 env->ReleaseIntArrayElements(device_ids_array, device_ids, JNI_ABORT);
1036 env->DeleteLocalRef(device_ids_array);
1037
1038 AddSensorDevice(env);
1039 }
1040
1041 } // namespace ciface::Android
1042
1043 extern "C" {
1044
1045 JNIEXPORT jboolean JNICALL
1046 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_dispatchKeyEventNative(
1047 JNIEnv* env, jclass, jobject key_event)
1048 {
1049 const jint action = env->CallIntMethod(key_event, s_key_event_get_action);
1050 ControlState state;
1051 switch (action)
1052 {
1053 case AKEY_EVENT_ACTION_DOWN:
1054 state = 1;
1055 break;
1056 case AKEY_EVENT_ACTION_UP:
1057 state = 0;
1058 break;
1059 default:
1060 return JNI_FALSE;
1061 }
1062
1063 const jint device_id = env->CallIntMethod(key_event, s_input_event_get_device_id);
1064 const std::shared_ptr<ciface::Core::Device> device = FindDevice(device_id);
1065 if (!device)
1066 return JNI_FALSE;
1067
1068 const jint keycode = env->CallIntMethod(key_event, s_key_event_get_keycode);
1069 const std::string input_name = ConstructKeyName(keycode);
1070
1071 ciface::Core::Device::Input* input = device->FindInput(input_name);
1072 if (!input)
1073 {
1074 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Could not find input {} in device {}", input_name,
1075 device->GetQualifiedName());
1076 return false;
1077 }
1078
1079 auto casted_input = static_cast<ciface::Android::AndroidInput*>(input);
1080 casted_input->SetState(state);
1081 const Clock::time_point last_polled = casted_input->GetLastPolled();
1082
1083 DEBUG_LOG_FMT(CONTROLLERINTERFACE, "Set {} of {} to {}", input_name, device->GetQualifiedName(),
1084 state);
1085
1086 return last_polled >= Clock::now() - ACTIVE_INPUT_TIMEOUT;
1087 }
1088
1089 JNIEXPORT jboolean JNICALL
1090 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_dispatchGenericMotionEventNative(
1091 JNIEnv* env, jclass, jobject motion_event)
1092 {
1093 const jint device_id = env->CallIntMethod(motion_event, s_input_event_get_device_id);
1094 const std::shared_ptr<ciface::Core::Device> device = FindDevice(device_id);
1095 if (!device)
1096 return JNI_FALSE;
1097
1098 const jint source = env->CallIntMethod(motion_event, s_motion_event_get_source);
1099 const std::string axis_name_prefix = ConstructAxisNamePrefix(source);
1100
1101 Clock::time_point last_polled{};
1102
1103 for (ciface::Core::Device::Input* input : device->Inputs())
1104 {
1105 const std::string input_name = input->GetName();
1106 if (input_name.starts_with(axis_name_prefix))
1107 {
1108 const std::string axis_id_str = input_name.substr(
1109 axis_name_prefix.size(), input_name.size() - axis_name_prefix.size() - sizeof('+'));
1110
1111 int axis_id;
1112 if (!TryParse(axis_id_str, &axis_id))
1113 {
1114 ERROR_LOG_FMT(CONTROLLERINTERFACE, "Failed to parse \"{}\" from \"{}\" as axis ID",
1115 axis_id_str, input_name);
1116 continue;
1117 }
1118
1119 float value = env->CallFloatMethod(motion_event, s_motion_event_get_axis_value, axis_id);
1120
1121 auto casted_input = static_cast<ciface::Android::AndroidInput*>(input);
1122 casted_input->SetState(value);
1123 last_polled = std::max(last_polled, casted_input->GetLastPolled());
1124
1125 DEBUG_LOG_FMT(CONTROLLERINTERFACE, "Set {} of {} to {}", input_name,
1126 device->GetQualifiedName(), value);
1127 }
1128 }
1129
1130 return last_polled >= Clock::now() - ACTIVE_INPUT_TIMEOUT;
1131 }
1132
1133 JNIEXPORT jboolean JNICALL
1134 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_dispatchSensorEventNative(
1135 JNIEnv* env, jclass, jstring j_device_qualifier, jstring j_axis_name, jfloat value)
1136 {
1137 ciface::Core::DeviceQualifier device_qualifier;
1138 device_qualifier.FromString(GetJString(env, j_device_qualifier));
1139 const std::shared_ptr<ciface::Core::Device> device =
1140 g_controller_interface.FindDevice(device_qualifier);
1141 if (!device)
1142 return JNI_FALSE;
1143
1144 const std::string axis_name = GetJString(env, j_axis_name);
1145
1146 Clock::time_point last_polled{};
1147
1148 for (ciface::Core::Device::Input* input : device->Inputs())
1149 {
1150 const std::string input_name = input->GetName();
1151 if (input_name == axis_name)
1152 {
1153 auto casted_input = static_cast<ciface::Android::AndroidInput*>(input);
1154 casted_input->SetState(value);
1155 last_polled = std::max(last_polled, casted_input->GetLastPolled());
1156 }
1157 }
1158
1159 return last_polled >= Clock::now() - ACTIVE_INPUT_TIMEOUT;
1160 }
1161
1162 JNIEXPORT void JNICALL
1163 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_notifySensorSuspendedState(
1164 JNIEnv* env, jclass, jstring j_device_qualifier, jobjectArray j_axis_names, jboolean suspended)
1165 {
1166 ciface::Core::DeviceQualifier device_qualifier;
1167 device_qualifier.FromString(GetJString(env, j_device_qualifier));
1168 const std::shared_ptr<ciface::Core::Device> device =
1169 g_controller_interface.FindDevice(device_qualifier);
1170 if (!device)
1171 return;
1172
1173 const std::vector<std::string> axis_names = JStringArrayToVector(env, j_axis_names);
1174
1175 for (ciface::Core::Device::Input* input : device->Inputs())
1176 {
1177 if (Common::Contains(axis_names, input->GetName()))
1178 {
1179 auto casted_input = static_cast<ciface::Android::AndroidSensorAxis*>(input);
1180 casted_input->NotifyIsSuspended(static_cast<bool>(suspended));
1181 }
1182 }
1183 }
1184
1185 JNIEXPORT void JNICALL
1186 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_00024InputDeviceListener_onInputDeviceAdded(
1187 JNIEnv* env, jobject, jint device_id)
1188 {
1189 ciface::Android::InputBackend::AddDevice(env, device_id);
1190 }
1191
1192 JNIEXPORT void JNICALL
1193 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_00024InputDeviceListener_onInputDeviceRemoved(
1194 JNIEnv*, jobject, jint device_id)
1195 {
1196 ciface::Android::InputBackend::RemoveDevice(device_id);
1197 }
1198
1199 JNIEXPORT void JNICALL
1200 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_00024InputDeviceListener_onInputDeviceChanged(
1201 JNIEnv* env, jobject, jint device_id)
1202 {
1203 // AddDevice will automatically remove the existing device
1204 ciface::Android::InputBackend::AddDevice(env, device_id);
1205 }
1206
1207 JNIEXPORT jobjectArray JNICALL
1208 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_getAllDeviceStrings(
1209 JNIEnv* env, jclass)
1210 {
1211 return SpanToJStringArray(env, g_controller_interface.GetAllDeviceStrings());
1212 }
1213
1214 JNIEXPORT jobject JNICALL
1215 Java_org_dolphinemu_dolphinemu_features_input_model_ControllerInterface_getDevice(
1216 JNIEnv* env, jclass, jstring j_device_string)
1217 {
1218 ciface::Core::DeviceQualifier qualifier;
1219 qualifier.FromString(GetJString(env, j_device_string));
1220 return CoreDeviceToJava(env, g_controller_interface.FindDevice(qualifier));
1221 }
1222 }