joypad_linux.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. /**************************************************************************/
  2. /* joypad_linux.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifdef JOYDEV_ENABLED
  31. #include "joypad_linux.h"
  32. #include <dirent.h>
  33. #include <errno.h>
  34. #include <fcntl.h>
  35. #include <linux/input.h>
  36. #include <unistd.h>
  37. #ifdef UDEV_ENABLED
  38. #ifdef SOWRAP_ENABLED
  39. #include "libudev-so_wrap.h"
  40. #else
  41. #include <libudev.h>
  42. #endif
  43. #endif
  44. #define LONG_BITS (sizeof(long) * 8)
  45. #define test_bit(nr, addr) (((1UL << ((nr) % LONG_BITS)) & ((addr)[(nr) / LONG_BITS])) != 0)
  46. #define NBITS(x) ((((x)-1) / LONG_BITS) + 1)
  47. #ifdef UDEV_ENABLED
  48. static const char *ignore_str = "/dev/input/js";
  49. #endif
  50. JoypadLinux::Joypad::~Joypad() {
  51. for (int i = 0; i < MAX_ABS; i++) {
  52. if (abs_info[i]) {
  53. memdelete(abs_info[i]);
  54. }
  55. }
  56. }
  57. void JoypadLinux::Joypad::reset() {
  58. dpad = 0;
  59. fd = -1;
  60. for (int i = 0; i < MAX_ABS; i++) {
  61. abs_map[i] = -1;
  62. curr_axis[i] = 0;
  63. }
  64. events.clear();
  65. }
  66. JoypadLinux::JoypadLinux(Input *in) {
  67. #ifdef UDEV_ENABLED
  68. #ifdef SOWRAP_ENABLED
  69. #ifdef DEBUG_ENABLED
  70. int dylibloader_verbose = 1;
  71. #else
  72. int dylibloader_verbose = 0;
  73. #endif
  74. use_udev = initialize_libudev(dylibloader_verbose) == 0;
  75. if (use_udev) {
  76. if (!udev_new || !udev_unref || !udev_enumerate_new || !udev_enumerate_add_match_subsystem || !udev_enumerate_scan_devices || !udev_enumerate_get_list_entry || !udev_list_entry_get_next || !udev_list_entry_get_name || !udev_device_new_from_syspath || !udev_device_get_devnode || !udev_device_get_action || !udev_device_unref || !udev_enumerate_unref || !udev_monitor_new_from_netlink || !udev_monitor_filter_add_match_subsystem_devtype || !udev_monitor_enable_receiving || !udev_monitor_get_fd || !udev_monitor_receive_device || !udev_monitor_unref) {
  77. // There's no API to check version, check if functions are available instead.
  78. use_udev = false;
  79. print_verbose("JoypadLinux: Unsupported udev library version!");
  80. } else {
  81. print_verbose("JoypadLinux: udev enabled and loaded successfully.");
  82. }
  83. } else {
  84. print_verbose("JoypadLinux: udev enabled, but couldn't be loaded. Falling back to /dev/input to detect joypads.");
  85. }
  86. #endif
  87. #else
  88. print_verbose("JoypadLinux: udev disabled, parsing /dev/input to detect joypads.");
  89. #endif
  90. input = in;
  91. monitor_joypads_thread.start(monitor_joypads_thread_func, this);
  92. joypad_events_thread.start(joypad_events_thread_func, this);
  93. }
  94. JoypadLinux::~JoypadLinux() {
  95. monitor_joypads_exit.set();
  96. joypad_events_exit.set();
  97. monitor_joypads_thread.wait_to_finish();
  98. joypad_events_thread.wait_to_finish();
  99. close_joypads();
  100. }
  101. void JoypadLinux::monitor_joypads_thread_func(void *p_user) {
  102. if (p_user) {
  103. JoypadLinux *joy = static_cast<JoypadLinux *>(p_user);
  104. joy->monitor_joypads_thread_run();
  105. }
  106. }
  107. void JoypadLinux::monitor_joypads_thread_run() {
  108. #ifdef UDEV_ENABLED
  109. if (use_udev) {
  110. udev *_udev = udev_new();
  111. if (!_udev) {
  112. use_udev = false;
  113. ERR_PRINT("Failed getting an udev context, falling back to parsing /dev/input.");
  114. monitor_joypads();
  115. } else {
  116. enumerate_joypads(_udev);
  117. monitor_joypads(_udev);
  118. udev_unref(_udev);
  119. }
  120. } else {
  121. monitor_joypads();
  122. }
  123. #else
  124. monitor_joypads();
  125. #endif
  126. }
  127. #ifdef UDEV_ENABLED
  128. void JoypadLinux::enumerate_joypads(udev *p_udev) {
  129. udev_enumerate *enumerate;
  130. udev_list_entry *devices, *dev_list_entry;
  131. udev_device *dev;
  132. enumerate = udev_enumerate_new(p_udev);
  133. udev_enumerate_add_match_subsystem(enumerate, "input");
  134. udev_enumerate_scan_devices(enumerate);
  135. devices = udev_enumerate_get_list_entry(enumerate);
  136. udev_list_entry_foreach(dev_list_entry, devices) {
  137. const char *path = udev_list_entry_get_name(dev_list_entry);
  138. dev = udev_device_new_from_syspath(p_udev, path);
  139. const char *devnode = udev_device_get_devnode(dev);
  140. if (devnode) {
  141. String devnode_str = devnode;
  142. if (devnode_str.find(ignore_str) == -1) {
  143. open_joypad(devnode);
  144. }
  145. }
  146. udev_device_unref(dev);
  147. }
  148. udev_enumerate_unref(enumerate);
  149. }
  150. void JoypadLinux::monitor_joypads(udev *p_udev) {
  151. udev_device *dev = nullptr;
  152. udev_monitor *mon = udev_monitor_new_from_netlink(p_udev, "udev");
  153. udev_monitor_filter_add_match_subsystem_devtype(mon, "input", nullptr);
  154. udev_monitor_enable_receiving(mon);
  155. int fd = udev_monitor_get_fd(mon);
  156. while (!monitor_joypads_exit.is_set()) {
  157. fd_set fds;
  158. struct timeval tv;
  159. int ret;
  160. FD_ZERO(&fds);
  161. FD_SET(fd, &fds);
  162. tv.tv_sec = 0;
  163. tv.tv_usec = 0;
  164. ret = select(fd + 1, &fds, nullptr, nullptr, &tv);
  165. /* Check if our file descriptor has received data. */
  166. if (ret > 0 && FD_ISSET(fd, &fds)) {
  167. /* Make the call to receive the device.
  168. select() ensured that this will not block. */
  169. dev = udev_monitor_receive_device(mon);
  170. if (dev && udev_device_get_devnode(dev) != nullptr) {
  171. String action = udev_device_get_action(dev);
  172. const char *devnode = udev_device_get_devnode(dev);
  173. if (devnode) {
  174. String devnode_str = devnode;
  175. if (devnode_str.find(ignore_str) == -1) {
  176. if (action == "add") {
  177. open_joypad(devnode);
  178. } else if (String(action) == "remove") {
  179. close_joypad(devnode);
  180. }
  181. }
  182. }
  183. udev_device_unref(dev);
  184. }
  185. }
  186. usleep(50000);
  187. }
  188. udev_monitor_unref(mon);
  189. }
  190. #endif
  191. void JoypadLinux::monitor_joypads() {
  192. while (!monitor_joypads_exit.is_set()) {
  193. DIR *input_directory;
  194. input_directory = opendir("/dev/input");
  195. if (input_directory) {
  196. struct dirent *current;
  197. char fname[64];
  198. while ((current = readdir(input_directory)) != nullptr) {
  199. if (strncmp(current->d_name, "event", 5) != 0) {
  200. continue;
  201. }
  202. sprintf(fname, "/dev/input/%.*s", 16, current->d_name);
  203. if (attached_devices.find(fname) == -1) {
  204. open_joypad(fname);
  205. }
  206. }
  207. }
  208. closedir(input_directory);
  209. usleep(1000000); // 1s
  210. }
  211. }
  212. void JoypadLinux::close_joypads() {
  213. for (int i = 0; i < JOYPADS_MAX; i++) {
  214. MutexLock lock(joypads_mutex[i]);
  215. Joypad &joypad = joypads[i];
  216. close_joypad(joypad, i);
  217. }
  218. }
  219. void JoypadLinux::close_joypad(const char *p_devpath) {
  220. for (int i = 0; i < JOYPADS_MAX; i++) {
  221. MutexLock lock(joypads_mutex[i]);
  222. Joypad &joypad = joypads[i];
  223. if (joypads[i].devpath == p_devpath) {
  224. close_joypad(joypad, i);
  225. }
  226. }
  227. }
  228. void JoypadLinux::close_joypad(Joypad &p_joypad, int p_id) {
  229. if (p_joypad.fd != -1) {
  230. close(p_joypad.fd);
  231. p_joypad.fd = -1;
  232. attached_devices.erase(p_joypad.devpath);
  233. input->joy_connection_changed(p_id, false, "");
  234. }
  235. p_joypad.events.clear();
  236. }
  237. static String _hex_str(uint8_t p_byte) {
  238. static const char *dict = "0123456789abcdef";
  239. char ret[3];
  240. ret[2] = 0;
  241. ret[0] = dict[p_byte >> 4];
  242. ret[1] = dict[p_byte & 0xF];
  243. return ret;
  244. }
  245. void JoypadLinux::setup_joypad_properties(Joypad &p_joypad) {
  246. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  247. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  248. int num_buttons = 0;
  249. int num_axes = 0;
  250. if ((ioctl(p_joypad.fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  251. (ioctl(p_joypad.fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  252. return;
  253. }
  254. for (int i = BTN_JOYSTICK; i < KEY_MAX; ++i) {
  255. if (test_bit(i, keybit)) {
  256. p_joypad.key_map[i] = num_buttons++;
  257. }
  258. }
  259. for (int i = BTN_MISC; i < BTN_JOYSTICK; ++i) {
  260. if (test_bit(i, keybit)) {
  261. p_joypad.key_map[i] = num_buttons++;
  262. }
  263. }
  264. for (int i = 0; i < ABS_MISC; ++i) {
  265. /* Skip hats */
  266. if (i == ABS_HAT0X) {
  267. i = ABS_HAT3Y;
  268. continue;
  269. }
  270. if (test_bit(i, absbit)) {
  271. p_joypad.abs_map[i] = num_axes++;
  272. p_joypad.abs_info[i] = memnew(input_absinfo);
  273. if (ioctl(p_joypad.fd, EVIOCGABS(i), p_joypad.abs_info[i]) < 0) {
  274. memdelete(p_joypad.abs_info[i]);
  275. p_joypad.abs_info[i] = nullptr;
  276. }
  277. }
  278. }
  279. p_joypad.force_feedback = false;
  280. p_joypad.ff_effect_timestamp = 0;
  281. unsigned long ffbit[NBITS(FF_CNT)];
  282. if (ioctl(p_joypad.fd, EVIOCGBIT(EV_FF, sizeof(ffbit)), ffbit) != -1) {
  283. if (test_bit(FF_RUMBLE, ffbit)) {
  284. p_joypad.force_feedback = true;
  285. }
  286. }
  287. }
  288. void JoypadLinux::open_joypad(const char *p_path) {
  289. int joy_num = input->get_unused_joy_id();
  290. int fd = open(p_path, O_RDWR | O_NONBLOCK);
  291. if (fd != -1 && joy_num != -1) {
  292. unsigned long evbit[NBITS(EV_MAX)] = { 0 };
  293. unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
  294. unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
  295. // add to attached devices so we don't try to open it again
  296. attached_devices.push_back(String(p_path));
  297. if ((ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
  298. (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
  299. (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0)) {
  300. close(fd);
  301. return;
  302. }
  303. // Check if the device supports basic gamepad events
  304. bool has_abs_left = (test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit));
  305. bool has_abs_right = (test_bit(ABS_RX, absbit) && test_bit(ABS_RY, absbit));
  306. if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) && (has_abs_left || has_abs_right))) {
  307. close(fd);
  308. return;
  309. }
  310. char uid[128];
  311. char namebuf[128];
  312. String name = "";
  313. input_id inpid;
  314. if (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) >= 0) {
  315. name = namebuf;
  316. }
  317. if (ioctl(fd, EVIOCGID, &inpid) < 0) {
  318. close(fd);
  319. return;
  320. }
  321. MutexLock lock(joypads_mutex[joy_num]);
  322. Joypad &joypad = joypads[joy_num];
  323. joypad.reset();
  324. joypad.fd = fd;
  325. joypad.devpath = String(p_path);
  326. setup_joypad_properties(joypad);
  327. sprintf(uid, "%04x%04x", BSWAP16(inpid.bustype), 0);
  328. if (inpid.vendor && inpid.product && inpid.version) {
  329. uint16_t vendor = BSWAP16(inpid.vendor);
  330. uint16_t product = BSWAP16(inpid.product);
  331. uint16_t version = BSWAP16(inpid.version);
  332. sprintf(uid + String(uid).length(), "%04x%04x%04x%04x%04x%04x", vendor, 0, product, 0, version, 0);
  333. input->joy_connection_changed(joy_num, true, name, uid);
  334. } else {
  335. String uidname = uid;
  336. int uidlen = MIN(name.length(), 11);
  337. for (int i = 0; i < uidlen; i++) {
  338. uidname = uidname + _hex_str(name[i]);
  339. }
  340. uidname += "00";
  341. input->joy_connection_changed(joy_num, true, name, uidname);
  342. }
  343. }
  344. }
  345. void JoypadLinux::joypad_vibration_start(Joypad &p_joypad, float p_weak_magnitude, float p_strong_magnitude, float p_duration, uint64_t p_timestamp) {
  346. if (!p_joypad.force_feedback || p_joypad.fd == -1 || p_weak_magnitude < 0.f || p_weak_magnitude > 1.f || p_strong_magnitude < 0.f || p_strong_magnitude > 1.f) {
  347. return;
  348. }
  349. if (p_joypad.ff_effect_id != -1) {
  350. joypad_vibration_stop(p_joypad, p_timestamp);
  351. }
  352. struct ff_effect effect;
  353. effect.type = FF_RUMBLE;
  354. effect.id = -1;
  355. effect.u.rumble.weak_magnitude = floor(p_weak_magnitude * (float)0xffff);
  356. effect.u.rumble.strong_magnitude = floor(p_strong_magnitude * (float)0xffff);
  357. effect.replay.length = floor(p_duration * 1000);
  358. effect.replay.delay = 0;
  359. if (ioctl(p_joypad.fd, EVIOCSFF, &effect) < 0) {
  360. return;
  361. }
  362. struct input_event play;
  363. play.type = EV_FF;
  364. play.code = effect.id;
  365. play.value = 1;
  366. if (write(p_joypad.fd, (const void *)&play, sizeof(play)) == -1) {
  367. print_verbose("Couldn't write to Joypad device.");
  368. }
  369. p_joypad.ff_effect_id = effect.id;
  370. p_joypad.ff_effect_timestamp = p_timestamp;
  371. }
  372. void JoypadLinux::joypad_vibration_stop(Joypad &p_joypad, uint64_t p_timestamp) {
  373. if (!p_joypad.force_feedback || p_joypad.fd == -1 || p_joypad.ff_effect_id == -1) {
  374. return;
  375. }
  376. if (ioctl(p_joypad.fd, EVIOCRMFF, p_joypad.ff_effect_id) < 0) {
  377. return;
  378. }
  379. p_joypad.ff_effect_id = -1;
  380. p_joypad.ff_effect_timestamp = p_timestamp;
  381. }
  382. float JoypadLinux::axis_correct(const input_absinfo *p_abs, int p_value) const {
  383. int min = p_abs->minimum;
  384. int max = p_abs->maximum;
  385. // Convert to a value between -1.0f and 1.0f.
  386. return 2.0f * (p_value - min) / (max - min) - 1.0f;
  387. }
  388. void JoypadLinux::joypad_events_thread_func(void *p_user) {
  389. if (p_user) {
  390. JoypadLinux *joy = (JoypadLinux *)p_user;
  391. joy->joypad_events_thread_run();
  392. }
  393. }
  394. void JoypadLinux::joypad_events_thread_run() {
  395. while (!joypad_events_exit.is_set()) {
  396. bool no_events = true;
  397. for (int i = 0; i < JOYPADS_MAX; i++) {
  398. MutexLock lock(joypads_mutex[i]);
  399. Joypad &joypad = joypads[i];
  400. if (joypad.fd == -1) {
  401. continue;
  402. }
  403. input_event event;
  404. while (read(joypad.fd, &event, sizeof(event)) > 0) {
  405. no_events = false;
  406. JoypadEvent joypad_event;
  407. joypad_event.type = event.type;
  408. joypad_event.code = event.code;
  409. joypad_event.value = event.value;
  410. joypad.events.push_back(joypad_event);
  411. }
  412. if (errno != EAGAIN) {
  413. close_joypad(joypad, i);
  414. }
  415. }
  416. if (no_events) {
  417. usleep(10000); // 10ms
  418. }
  419. }
  420. }
  421. void JoypadLinux::process_joypads() {
  422. for (int i = 0; i < JOYPADS_MAX; i++) {
  423. MutexLock lock(joypads_mutex[i]);
  424. Joypad &joypad = joypads[i];
  425. if (joypad.fd == -1) {
  426. continue;
  427. }
  428. for (uint32_t j = 0; j < joypad.events.size(); j++) {
  429. const JoypadEvent &joypad_event = joypad.events[j];
  430. // joypad_event may be tainted and out of MAX_KEY range, which will cause
  431. // joypad.key_map[joypad_event.code] to crash
  432. if (joypad_event.code >= MAX_KEY) {
  433. return;
  434. }
  435. switch (joypad_event.type) {
  436. case EV_KEY:
  437. input->joy_button(i, (JoyButton)joypad.key_map[joypad_event.code], joypad_event.value);
  438. break;
  439. case EV_ABS:
  440. switch (joypad_event.code) {
  441. case ABS_HAT0X:
  442. if (joypad_event.value != 0) {
  443. if (joypad_event.value < 0) {
  444. joypad.dpad.set_flag(HatMask::LEFT);
  445. joypad.dpad.clear_flag(HatMask::RIGHT);
  446. } else {
  447. joypad.dpad.set_flag(HatMask::RIGHT);
  448. joypad.dpad.clear_flag(HatMask::LEFT);
  449. }
  450. } else {
  451. joypad.dpad.clear_flag(HatMask::LEFT);
  452. joypad.dpad.clear_flag(HatMask::RIGHT);
  453. }
  454. input->joy_hat(i, joypad.dpad);
  455. break;
  456. case ABS_HAT0Y:
  457. if (joypad_event.value != 0) {
  458. if (joypad_event.value < 0) {
  459. joypad.dpad.set_flag(HatMask::UP);
  460. joypad.dpad.clear_flag(HatMask::DOWN);
  461. } else {
  462. joypad.dpad.set_flag(HatMask::DOWN);
  463. joypad.dpad.clear_flag(HatMask::UP);
  464. }
  465. } else {
  466. joypad.dpad.clear_flag(HatMask::UP);
  467. joypad.dpad.clear_flag(HatMask::DOWN);
  468. }
  469. input->joy_hat(i, joypad.dpad);
  470. break;
  471. default:
  472. if (joypad_event.code >= MAX_ABS) {
  473. return;
  474. }
  475. if (joypad.abs_map[joypad_event.code] != -1 && joypad.abs_info[joypad_event.code]) {
  476. float value = axis_correct(joypad.abs_info[joypad_event.code], joypad_event.value);
  477. joypad.curr_axis[joypad.abs_map[joypad_event.code]] = value;
  478. }
  479. break;
  480. }
  481. break;
  482. }
  483. }
  484. joypad.events.clear();
  485. for (int j = 0; j < MAX_ABS; j++) {
  486. int index = joypad.abs_map[j];
  487. if (index != -1) {
  488. input->joy_axis(i, (JoyAxis)index, joypad.curr_axis[index]);
  489. }
  490. }
  491. if (joypad.force_feedback) {
  492. uint64_t timestamp = input->get_joy_vibration_timestamp(i);
  493. if (timestamp > joypad.ff_effect_timestamp) {
  494. Vector2 strength = input->get_joy_vibration_strength(i);
  495. float duration = input->get_joy_vibration_duration(i);
  496. if (strength.x == 0 && strength.y == 0) {
  497. joypad_vibration_stop(joypad, timestamp);
  498. } else {
  499. joypad_vibration_start(joypad, strength.x, strength.y, duration, timestamp);
  500. }
  501. }
  502. }
  503. }
  504. }
  505. #endif // JOYDEV_ENABLED